phparraysmultidimensional-arrayappend

Append a new column with a fixed value to each row of a 2d array


I have an array that looks like this:

$array = [
    [
        'title' => 'Ireland - Wikipedia, the free encyclopedia',
        'url' => 'http://example.com/wiki/Ireland'
    ],
    [
        'title' => 'Ireland\'s home for accommodation, activities.',
        'url' => 'http://www.example.com/'
    ]
];

I want to add a score element with a value of 0 to each row. I thought this simple foreach loop would do the trick, but...well....it doesn't. :/

public function setScore($result)
{
    foreach($result as $key)
    {
        $key = array('title', 'url', 'score' => 0);
    }
    return $result;
}

Can someone help me out?


Solution

  • You create a new array here and do nothing with it:

     foreach($result as $key){
         $key = array('title', 'url', 'score' => 0);
     }
    

    What you want to do is to modify a reference to existing one:

     foreach($result as &$key){  # Note the '&' here
         $key['score'] = 0;
     }