简体   繁体   English

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

[英]Appending elements to an array in a multidimensional array php?

Within a foreach loop, I get the following values: foreach循环中,得到以下值:

$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: 现在,同一个名称可能会使用不同的ID多次出现,我想像这样形成数组:

$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. 因此,不太确定如何执行此操作。

You need to append to the sub-array, not assign it directly. 您需要追加到子数组,而不是直接分配它。 And if $name doesn't yet exist, you need to add it. 如果$name还不存在,则需要添加它。

$data = array();
foreach ($rows as $row)
{
  $name = $row->name;
  $id = $row->id;
  if (isset($data[$name])) {
    $data[$name][] = $id;
  } else {
    $data[$name] = array($id);
  }
}

If there is no value for your name , you need just to add it , else you append value to existing ones : 如果您的名字没有值,则只需添加它,否则将值附加到现有值上:

$data = array();

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

    if (isset( $data[$name]) && is_array( $data[$name]) ) {
       $data[$name][] = $id; 
    }
    else {$data[$name] = array($id);}


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM