2017-08-28 29 views
0

でmysqlのクエリから2D-アレイの作成: Query Result私は私のクエリで、この次の結果を持っているPHP

私はPHPで、このような配列を作成しようとしています:

[ 
    { 
     "software_version": "1.0", 
     "version_date": "10/08/2016", 
     "changelog": [ 
      { 
       "type": "IMP", 
       "description": "Initial version." 
      } 
     ] 
    }, 
    { 
     "software_version": "1.0.1", 
     "version_date": "27/07/2017", 
     "changelog": [ 
      { 
       "type": "ADD", 
       "description": "HostPanel update manager." 
      }, 
     { 
       "type": "ADD", 
       "description": "Hook OnDaemonMinute." 
      } 
     ] 
    } 
] 

私がする必要があります結果をsoftware_version行と組み合わせてください。 何か助けていただければ幸いです。

私のPHPコード:

$changelog = array(); 
foreach ($result as $r) { 
    $changelog[] = array(
     'software_version' => $r['software_version'], 
     'version_date' => $r['version_date'], 
     'changelog' => array(
          array(
           'type' => 'IMP', // help 
           'description' => 'Initial version.' 
          ) 
         ) 
    ); 
} 
+0

なぜあなたはあなたのPHPコードを削除しましたか? –

+0

@ Don'tPanic私はそれを巻き戻しました。 –

答えて

1

キーは、あなたがそれを構築するよう$changelogでキーとしてソフトウェアのバージョンを使用することです。

$changelog = array(); 
foreach ($result as $r) { 

    // get the version (just to make the following code more readable) 
    $v = $r['software_version']; 

    // create the initial entry for the version if it doesn't exist yet 
    if (!isset($changelog[$v]) { 
     $changelog[$v] = ['software_version' => $v, 'version_date' => $r['version_date']]; 
    } 

    // create an entry for the type/description pair 
    $change = ['type' => $r['type'], 'description' => $r['description']]; 

    // add it to the changelog for that version 
    $changelog[$v]['changelog'][] = $change; 
} 

あなたはJSONはあなたが行っているJSON配列出力を生成するために、それをコードする前$changelogのインデックスを再作成するためにarray_valuesを使用する必要があります。

$changelog = array_values($changelog); 
+0

ありがとうございました、あなたの答えは私の多くを助けました、私は変数型で小さな変更を行った行です。 –

+1

おっと、ねえ、それをキャッチするために感謝します。 (そのため、テストせずに回答を投稿しないようにする必要があります。) –

関連する問題