2016-07-07 66 views
0

我有這樣一個數組:爆炸的字符串,然後將結果數組回到陣

array:3 [▼ 
    0 => {#472 ▼ 
    +"component_id": 3 
    +"supplier_id": 1 
    +"volumes": "100:1.5000,207:1.0100,500:0.8000,1000:0.4000" 
    } 
    1 => {#474 ▼ 
    +"component_id": 3 
    +"supplier_id": 2 
    +"volumes": "10000:0.2000" 
    } 
    2 => {#475 ▼ 
    +"component_id": 4 
    +"supplier_id": 2 
    +"volumes": "100:0.1000,500:0.0700" 
    } 
] 

我要爆炸了「量」的一部分,並創建它自己的陣列出來,像這樣結束了:

[ 
    "component_id" => 4 
    "supplier_id" => 2 
    "volumes" => array:3 [▼ 
     100 => "0.1000", 
     500 => "0.0700" 
    ] 
] 

我已經嘗試了一些東西,這是最接近到目前爲止,我已經得到了(NB使用Laravel 5.2):

$components = DB::select(
       'SELECT component_id, supplier_id, 
       GROUP_CONCAT(volume, \':\', unit_cost) AS volumes 
       FROM component_supplier 
       GROUP BY CONCAT(component_id, supplier_id)' 
       ); 

     foreach ($components as $component) { 
      $exploded = explode(",",$component->volumes); 
      array_push($components, $exploded); 
     } 

哪更接近!但是,僅僅追加排序的正確格式到數組的結尾 - 這是我將從array_push想到我猜:)

array:6 [▼ 
    0 => {#472 ▼ 
    +"component_id": 3 
    +"supplier_id": 1 
    +"volumes": "100:1.5000,207:1.0100,500:0.8000,1000:0.4000" 
    } 
    1 => {#474 ▼ 
    +"component_id": 3 
    +"supplier_id": 2 
    +"volumes": "10000:0.2000" 
    } 
    2 => {#475 ▼ 
    +"component_id": 4 
    +"supplier_id": 2 
    +"volumes": "100:0.1000,500:0.0700" 
    } 
    3 => array:4 [▼ 
    0 => "100:1.5000" 
    1 => "207:1.0100" 
    2 => "500:0.8000" 
    3 => "1000:0.4000" 
    ] 
    4 => array:1 [▼ 
    0 => "10000:0.2000" 
    ] 
    5 => array:2 [▼ 
    0 => "100:0.1000" 
    1 => "500:0.0700" 
    ] 
] 

所以我掙扎爆炸它,把它變成一個關鍵= >值格式,然後(最重要的是),在正確的位置將其推回到數組中。

感謝您的幫助:)

回答

0
foreach ($components as $component) { 
    $volumesList = explode(',', $component->volumes); 
    $volumesDictionary = []; 
    foreach ($volumesList as $listItem) { 
     list($key, $value) = explode(':', $listItem); 
     $volumesDictionary[$key] = $value; 
    } 
    $component->volumes = $volumesDictionary; 
} 

說明: 項目之間用逗號隔開,鍵值對用冒號分隔。所以我們必須爆炸兩次。將鍵與值分開後,我們將它們添加到字典中。最後,我們想用一個關聯數組替換序列化字典,所以不是調用array_push(它總是將項追加到數組的末尾,而不是到項的最後一項的數組),我們只需替換$component->volumes字符串與新創建的字典。

+1

感謝瘋狗的解釋和示例代碼,這是真正有用的和內容豐富。 – trh88

0

它看起來像你需要兩個爆炸。像這樣的東西。

foreach ($components as $component) { 

     $exploded = explode(",",$component->volumes); 

     foreach($exploded as $item) 
     { 
      $ex_item = explode(':', $item); 
      $components[$ex_item[0]] = $ex_item[1]; 
     } 
    }