2016-11-17 10 views
1

mysqlの戻り値からデータ配列を作成したいとします。 MySQLからの生データがある:Morrisの配列で応答データを作成する方法

foreach($chart as $hotel=>$rep){ 
    echo "{hotel:$hotel, $rep},"; 
} 

そして結果は次のとおりです:

だから、
{ 
hotel: 'BD', 
    Eid:59100, 
    Mona:156050, 
    Nai:27750, 
    Nana:90680, 
    Pinya:9400, 
    Pok:43900, 
    Tunk:48600, 
    VEE:26800, 
}... 

、私が書く:

$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, Array},{hotel:cp, Array},{hotel:cs, Array},{hotel:km, Array}{hotel:nk, Array}, 

これは欲しいものに似ていますbどのように上記の形式にArrayを抽出できますか?

答えて

2

このコードの作品を​​。

$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; 
+1

ありがとうございます、あなたのソリューションは魅力のように動作します! – Wilf

+0

あなたはようこそ(Y) –

0

この作品のようなものはありますか?

// 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} 
+0

申し訳ありませんが、あなたの回答は私と同じものを返します。 {hotel:bd、Eid:}、{hotel:cp、Eid:}、{hotel:cs、Eid:}、{hotel:km、Eid:、}、{hotel:nh、Eid :,} 、{hotel:nk、Eid:、} ' – Wilf

+0

私に知らせてくれてありがとう。私は自分のコードを更新しました – atoms

+0

良いですが、私も 'ホテル '値が欲しいです:D – Wilf

関連する問題