2017-08-28 148 views
0

創建二維數組我有這樣的結果之後,我查詢: Query Result從MySQL查詢在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; 
} 

你需要使用array_values JSON編碼它以產生你要去的JSON陣列輸出前重新索引$changelog

$changelog = array_values($changelog); 
+0

謝謝你,你的回答幫了我很多,我做了一個小改動,變量類型是連續的。 –

+1

哎呀,是的,謝謝你的發現。 (這就是爲什麼我們應該儘量避免在沒有測試的情況下發布答案。) –