KTAnj
KTAnj

Reputation: 1356

Append a new column with a static value to a pre-populated 2d array

$array = array(
    array("a" => 1),
    array("a" => 2)
);

I need to push data to sub array element in $array,

End result must be as follow,

Array (
    [0] => Array (
        [a] => 1
        [b] => 2
    )
    [1] => Array (
        [a] => 2
        [b] => 2
    )
)

I used following ways.

  1. foreach ($array as &$a) { 
        $a['b'] = 2;
    }
    
  2. $result = array_map("pushdata", $array);
    function pushdata($a) {
        $a['b'] = 2;
    }
    

What is the most suitable and efficient way when $array consists of more than 1000 records?

Upvotes: 0

Views: 97

Answers (4)

mickmackusa
mickmackusa

Reputation: 48071

A foreach() loop is handy because the new column can be setting by reference without accessing any of the pre-existing row data.

foreach ($array as ['b' => &$b]) {
    $b = 2;
}
var_export($array);

array_walk() has the unique features of passing a non-iterated 3rd parameter.

array_walk(
    $array,
    fn(&$row, $_, $extra) => $row += $extra,
    ['b' => 2]
);
var_export($array);

The callback of array_map() can leverage the array union operator to merge each row with the new column.

var_export(
    array_map(
        fn($row) => $row + ['b' => 2],
        $array
    )
);

Upvotes: 0

Cyclonecode
Cyclonecode

Reputation: 30131

Here is an example using array_walk() to add a new key b to each sub-array:

$array = array(array('a' => 1), array('a' => 2));
array_walk($array, function(&$item, $key) {
  $item['b'] = 2;
});
print_r($array);
/* outputs:
Array
(
  [0] => Array
  (
      [a] => 1
      [b] => 2
  )
  [1] => Array
  (
      [a] => 2
      [b] => 2
  )
)
*/

Upvotes: 1

Althaf M
Althaf M

Reputation: 508

Use array_walk , to iterate over the array and array_push to push the element to each iteration.

Upvotes: 1

Riad
Riad

Reputation: 3870

Here is an example for 5 items.

<?php

  for($i = 1 ; $i<5 ; $i++){
     $array[] = array("a"=>$i,"b"=>2);
  }

  print_r($array);

?>

See online

Upvotes: 1

Related Questions