2017-09-16 538 views
0

我正在Laravel工作。我有兩個數組,我想在第一個數組中插入第二個數組作爲值。例如,給定在laravel的另一個數組的鍵上添加數組

$firstArray = [ 
    'id' => 1, 
    'propery_name' => 'Test Property' 
]; 

$secondArray = [ 
    'id' => 2, 
    'user_name' => 'john' 
]; 

,我想生產的

$resultArray = [ 
    'id' => 1, 
    'propery_name' => 'Test Property', 
    'userData' => [ 
     'id' => 2, 
     'user_name' => 'john' 
    ] 
]; 

等效我怎樣才能做到這一點?

回答

0
$resultArray = $firstArray; 
$resultArray['userData'] = $secondArray; 
0

試試這個:

$firstArray = ['id'=>1,'propery_name'=>'Test Property']; 
    $secondArray = ['id'=>2,'user_name'=>'john']; 

    $resultArray = ['property' => $firstArray, 'userData' => $secondArray]; 

新創建的陣列應該給你:

{{ $resultArray['userData']['user_name'] }} = John 

    {{ $resultArray['property']['propery_name'] }} = Test Property 
0
$firstArray['userData'] = $secondArray; 

return $firstArray; 

//result 

$resultArray = [ 
    'id' => 1, 
    'propery_name' => 'Test Property', 
    'userData' => [ 
     'id' => 2, 
     'user_name' => 'john' 
    ] 
]; 
0

您可以使用Laravel集合類此。推送函數是在數組中添加值的最佳方式。 https://laravel.com/docs/5.5/collections#method-put

在你的情況,

$firstArray = [ 
    'id' => 1, 
    'propery_name' => 'Test Property' 
]; 

$secondArray = [ 
    'id' => 2, 
    'user_name' => 'john' 
]; 
$collection = collect($firstArray); 
$collection->put('userData', $secondArray); 
$collection->all(); 

輸出:

['id' => 1, 
    'propery_name' => 'Test Property', 
    'userData' => [ 
     'id' => 2, 
     'user_name' => 'john' 
    ] 
]; 
相關問題