将元素添加到数组中

sha*_*o86 1 php multidimensional-array

我有一个看起来像这样的数组:

array
  0 => 
    array
      'title' => string 'Ireland - Wikipedia, the free encyclopedia'
      'url' => string 'http://en.wikipedia.org/wiki/Ireland'
  1 => 
    array
      'title' => string 'Ireland's home for accommodation, activities.'
      'url' => string 'http://www.ireland.com/'
Run Code Online (Sandbox Code Playgroud)

我想为每个元素添加0分.我认为这个简单的foreach循环可以做到这一点但是......好吧......它不会:/

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

有人可以帮我吗?

谢谢

dec*_*eze 6

foreach适用于数组的副本.你可以修改$key你想要的所有内容,它不会反映在原始数组上.

您可以$key 通过引用使用,然后它将按预期工作:

foreach ($result as &$value) {
    $value['score'] = 0;
}
Run Code Online (Sandbox Code Playgroud)

手动输入: http ://php.net/manual/en/control-structures.foreach.php