2017-09-16 41 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' 
    ] 
]; 
相关问题