Hommer Smith
Hommer Smith

Reputation: 27852

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...

Upvotes: 3

Views: 99

Answers (4)

pikax
pikax

Reputation: 259

You could do like this:

$arrayUsers = array();//declare array

$arrUser = array("id"=>"23","myvalue"=>NULL); //User 23
$arrayUsers[$arrUser["id"]] = $arrUser; //add

$arrUser = array("id"=>"62","myvalue"=>NULL); //User 62
$arrayUsers[$arrUser["id"]] = $arrUser; //add

var_dump($arrayUsers);

the result is this:

array(2) 
{ 
    [23]=> array(2) 
    { 
        ["id"]=> string(2) "23" 
        ["myvalue"]=> NULL 
    }

    [62]=> array(2) 
    { 
        ["id"]=> string(2) "62" 
        ["myvalue"]=> NULL 
    } 
} 

[EDIT]

$valueArray = array();

foreach($arrayUsers as $id=>$value)
{
    $val = ($value["myvalue"]===NULL?100:$value["myvalue"]);
    $valueArray[$id] = $val;
}

var_dump($valueArray);

This should behave like you want

Upvotes: 1

Angelo Berçacola
Angelo Berçacola

Reputation: 173

you should do it:

foreach($old_array as $value)
$new_array[$value['id']]= ($value['my_value']!==NULL) ? $value['my_value'] : 100 ;

the result will be

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

running code example at Codepad.org

Upvotes: 0

dnagirl
dnagirl

Reputation: 20456

$arr = array(5 => array('id'=>23, 'myvalue'=>null),
             1 => array('id'=>62, 'myvalue'=>null));

$callback = function($v) { 
  $id = $v['id'];
  $myv = !is_null($v['myvalue']) ? $v['myvalue'] : 100;
  return array($id=>$myv);

}
$newarr = array_map($callback, $arr);

Upvotes: 0

aykut
aykut

Reputation: 3094

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'];
}

Upvotes: 1

Related Questions