我想从mysql的返回值创建一个数据数组。mysql的原始数据是:
$chart=Array (
[bd] => Array (
[Eid] => 59100
[Mona] => 156050
[Nai] => 27750
[Nana] => 90680
[Pinya] => 9400
[Pok] => 43900
[Tunk] => 48600
[VEE] => 26800
)
[cp] => Array (
[Eid] => 23650
[Mona] => 86760
[Nai] => 54160
[Nana] => 125300
[Pinya] => 63960
[Pok] => 59800
[Tunk] => 111260
[VEE] => 125460
)
)
我希望最终结果是这样的格式:
{
hotel: 'BD',
Eid:59100,
Mona:156050,
Nai:27750,
Nana:90680,
Pinya:9400,
Pok:43900,
Tunk:48600,
VEE:26800,
}...
所以,我写:
foreach($chart as $hotel=>$rep){
echo "{hotel:$hotel, $rep},";
}
结果是:
{hotel:bd, Array},{hotel:cp, Array},{hotel:cs, Array},{hotel:km, Array}{hotel:nk, Array},
它与我想要的相似,但是我如何将Array
提取成上面所示的格式?
此代码有效
$finalArray = array();
$i = 0;
foreach($chart as $hotel=>$rep) {
$finalArray[$i] = "{<br>hotel: $hotel,<br>";
foreach($rep as $key=>$val) {
$finalArray[$i] .= "$key:$val,<br>";
}
$finalArray[$i] .= "}<br>";
$i++;
}
$finalString = implode(",",$finalArray);
echo $finalString;
这样的东西会起作用吗?
// set empty string
$sOutput = '';
// loop over each char data using its key as the hotel id/ref
foreach ($chart as $sHotelID => $aHotelData) {
// if there is already output add a comma to the end
if($sOutput != '') $sOutput .= ",";
// add the opening brace and hotel info
$sOutput .= "{hotel:".$sHotelID.",";
// set empty string
$sTempOutput = '';
// loop over each hotel data entry storing into tempOutput
foreach ($aHotelData as $sKey => $sValue) {
if($sTempOutput != '') $sTempOutput .= ",";
$sTempOutput .= $sKey.":".$sValue;
}
// assign the tempoutput to the main output
$sOutput .= $sTempOutput."}";
}
var_export($sOutput);
这给了我:
{Eid:59100,Mona:156050,Nai:27750,Nana:90680,Pinya:9400,Pok:43900,Tunk:48600,VEE:26800},
{Eid:23650,Mona:86760,Nai:54160,Nana:125300,Pinya:63960,Pok:59800,Tunk:111260,VEE:125460}