追加元素添加到阵列中的多维数组PHP? [英] Appending elements to an array in a multidimensional array php?
本文介绍了追加元素添加到阵列中的多维数组PHP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在一个的foreach
循环,我得到以下值:
Within a foreach
loop, I get the following values:
$name = 'foo';
$id = '1';
现在,同样的名字可以以不同的ID出现多次,我想以形成阵列是这样的:
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'));
我曾尝试:
$data = array();
foreach ($rows as $row)
{
$name = $row->name;
$id = $row->id;
$data[$name] = $id;
}
然而,这一切都将返回是:
However, All this returns is:
最后一个值:
$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.
$data = array();
foreach ($rows as $row)
{
$name = $row->name;
$id = $row->id;
if (isset($data[$name])) {
$data[$name][] = $id;
} else {
$data[$name] = array($id);
}
}
这篇关于追加元素添加到阵列中的多维数组PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文