2016-04-02 103 views
-1

嗨我有一個數組,我已經添加了一個id到每個數組的鍵,但我希望該id也被添加到數組值。如何在PHP中將數組的鍵添加到數組值?

將鍵和值添加到數組的代碼。

foreach ($data as $id => $name) { 
      $arr[$id] = Category::where('parent_category_id', $id)->lists('id'); 
     } 

現在陣列看起來像這樣

Array 
(
    [427] => Illuminate\Support\Collection Object 
     (
      [items:protected] => Array 
       (
        [0] => 277 
        [1] => 279 
        [2] => 426 
        [3] => 428 
        [4] => 429 
        [5] => 430 
        [6] => 431 
        [7] => 432 
        [8] => 433 
        [9] => 434 
       ) 

     ) 

    [280] => Illuminate\Support\Collection Object 
     (
      [items:protected] => Array 
       (
        [0] => 281 
        [1] => 282 
        [2] => 435 
        [3] => 436 
        [4] => 437 
       ) 

     ) 

    [283] => Illuminate\Support\Collection Object 
     (
      [items:protected] => Array 
       (
        [0] => 284 
        [1] => 285 
        [2] => 286 
       ) 

     ) 

我真正想實現的是,我想補充例如說第一個關鍵是427到數組值,這樣我的鑰匙獲取所有的ID。我將如何能夠實現這一點,請協助。

回答

1

我以下面的代碼這樣做:

$result = []; 
array_walk($arr,function($v,$k)use (&$result){ 
    array_unshift($v,$k); 
    $result[$k][] = $v; 
}); 

print_r($result); 

您可以檢查工作演示here