Home > Net >  how to add an array inside another in PHP?
how to add an array inside another in PHP?

Time:11-26

I am using laravel. How can I create a new array and have the properties of another. Example the carriage array can have 3 rows that are of the "info" properties, but the brand is added.

    $info = [
      ['id' => 1, 'color'=> 'blue'],
      ['id' => 2, 'color'=> 'red'],
      ['id' => 3, 'color'=> 'yellow'],
    ];

    $car = [
      ['id' => 'id_info', 'brand'=> 'toyota', 'color' => 'color_info']  
    ];

CodePudding user response:

You can loop through array and add key to each array

$info = [
      ['id' => 1, 'color'=> 'blue'],
      ['id' => 2, 'color'=> 'red'],
      ['id' => 3, 'color'=> 'yellow'],
    ];
$newInfo = [];
foreach($info as $eachInfo){
  $newInfo[] = array_merge($eachInfo,['brand' => 'toyota']);
}

dd($newInfo);

Will produce output like

array:3 [
  0 => array:3 [
    "id" => 1
    "color" => "blue"
    "brand" => "toyota"
  ]
  1 => array:3 [
    "id" => 2
    "color" => "red"
    "brand" => "toyota"
  ]
  2 => array:3 [
    "id" => 3
    "color" => "yellow"
    "brand" => "toyota"
  ]
]
  • Related