我正在尝试使用一个平面数组并重新创建它,以便它是多维的。我一直在研究array_combine和array_merge,但我不确定其中任何一个会给我我希望的东西......
数组,以它的当前形式(这只是一个简化的例子):
Array
(
[0] => stdClass Object
(
[tid] => 31
[name] => Safeway
[parents] => Array
(
[0] => 0
)
)
[1] => stdClass Object
(
[tid] => 32
[name] => Dairy
[parents] => Array
(
[0] => 31
)
)
[2] => stdClass Object
(
[tid] => 33
[name] => Milk
[parents] => Array
(
[0] => 32
)
)
)
我正在尝试创建一个多维数组,其中每个对象都是它父类的子数组。所以,在上面的例子中,我试图输出:
Array
(
[0] => stdClass Object
(
[tid] => 31
[name] => Safeway
[children] => Array
(
[tid] => 32
[name] => Dairy
[children] => Array
(
[tid] => 33
[name] => Milk
)
)
)
)
答案 0 :(得分:1)
首先,你所展示的不是一个多维数组,而是一个StdClass对象数组。
如果您可以将它们设为真正的数组,那么这可能会这样做:
// initiate result array
$multiArray = array();
// assume $items is your current array
foreach( $items as $item )
{
// cast StdClass to array
$objToArray = (array) $item;
// if this item is initiated already merge it with the current item
$multiArray[ $objToArray[ 'tid' ] ] = isset( $multiArray[ $objToArray[ 'tid' ] ] ) ? $multiArray[ $objToArray[ 'tid' ] ] + $objToArray : $objToArray;
foreach( $objToArray[ 'parents' ] as $parentId )
{
// if parents don't exist yet, initiate them
if( !isset( $multiArray[ $parentId ] ) )
{
$multiArray[ $parentId ] = array(
'children' => array()
);
}
// add this item to the parents children collection by reference (for efficiency)
$multiArray[ $parentId ][ 'children' ][ $objToArray[ 'tid' ] ] = &$multiArray[ $objToArray[ 'tid' ] ];
}
}
有了这个,您可以通过ID轻松找到项目:
$item = $multiArray[ $someId ];
为了得到一个孩子:
$child = $item[ 'children' ][ $someChildId ];
或所有孩子:
$children = $item[ 'children' ];
修改强>
好的,我现在已经测试过了,添加一些缺失的分号后似乎工作正常。
答案 1 :(得分:0)
好的,我在这里做了一些假设:
parents
数组只有1个tid 鉴于此,请尝试以下代码:
$original = array ( ... your original array ... );
$nested = array ();
$n = count($original);
for ($i = 0; $i < $n; ++$i)
{
$nested[$original[$i]->tid] = $original[$i];
$nested[$original[$i]->tid]->children = array ();
}
while ($n-- && $current = $original[$n])
if ($current->parents[0] != 0 && $current->parents[0] != $current->tid)
{
$nested[$current->parents[0]]->children[] = $current;
unset ($nested[$current->tid]);
}