3

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

0

4 Answers 4

1

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'];
}
Sign up to request clarification or add additional context in comments.

1 Comment

aykut this solution won't change the indexs of the array...I want the new index to be taken from the other value in each row. Check my question, I want to change the indexs so they can take the values that are in the "id" key of each array.
1

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

Comments

0
$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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.