dou448172583 2014-01-09 09:08
浏览 43
已采纳

将元素附加到多维数组php中的数组?

Within a foreach loop, I get the following values:

$name = 'foo';
$id = '1';

Now, the same name may appear multiple times with different ID's and I would like to form as array like this:

$data = array('foo' => array('1','2','3'), 
              'bar' => array('4','7','98'),
              'nee' => array('12','45','45'));

I have tried:

$data = array();

foreach ($rows as $row)
{
   $name = $row->name;
   $id = $row->id;

   $data[$name] = $id;
}

However, All this returns is:

The last value:

$data = array(   'foo' => '3', 
                  'bar' => '98',
                  'nee' => '45');

So not too sure how to do this.

  • 写回答

2条回答 默认 最新

  • dongqianzhan8325 2014-01-09 09:12
    关注

    You need to append to the sub-array, not assign it directly. And if $name doesn't yet exist, you need to add it.

    $data = array();
    foreach ($rows as $row)
    {
      $name = $row->name;
      $id = $row->id;
      if (isset($data[$name])) {
        $data[$name][] = $id;
      } else {
        $data[$name] = array($id);
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?