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条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?