Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array with keys coming from multiple arrays

I have an array that looks like this:

array(5) {
  [0]=>
  array(2) {
    ["id"]=>
    string(2) "23"
    ["my_value"]=>
    NULL
  }
  [1]=>
  array(2) {
    ["id"]=>
    string(2) "62"
    ["my_value"]=>
    NULL
  }
...

I would like to have an array that as keys have the value of the key "id" in each array and as value have the value of "my_value". However if "my_value" is NULL I want to set a value of 100.

So, the result array would be like this:

array(5) {
      [23] => 100
      [62] => 100
...

How can I do that cleanly? I have been iterating over with a foreach but I believe it can be done cleaner...

like image 862
Hommer Smith Avatar asked May 24 '26 20:05

Hommer Smith


1 Answers

You can use array_map() for populate my_value

$newData = array_map(function($row) {
    if ( $row['my_value'] === null ) $row['my_value'] = 100;
    return $row;
}, $data);

But you already need a foreach loop because of formatting. So try this:

$newData = array();
foreach ($data as $row) {
    $newData[$row['id']] = ($row['my_value'] === null) ? 100 : $row['my_value'];
}
like image 111
aykut Avatar answered May 27 '26 11:05

aykut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!