如何基于主键和外键输出数组

时间:2010-11-24 17:43:02

标签: php

考虑这个数组

Array
(
[0] => Array
    (
        [id] => 51
        [category_id] => 37
        [title] => Sims
    )

[1] => Array
    (
        [id] => 37
        [category_id] => 26
        [title] => Blackberry
    )

[2] => Array
    (
        [id] => 26
        [category_id] => 0
        [title] => Mobile Device
    )

我希望能打印出来:

Mobile Device > Blackberry > Sims

基于category_id和id。

之间的关系

4 个答案:

答案 0 :(得分:1)

你可以使用id作为数组的密钥吗?它会让你的生活更简单。例如,如果您定义数组:

Array
(
[51] => Array
    (
        [id] => 51
        [category_id] => 37
        [title] => Sims
    )

[37] => Array
    (
        [id] => 37
        [category_id] => 26
        [title] => Blackberry
    )

[27] => Array
    (
        [id] => 26
        [category_id] => 0
        [title] => Mobile Device
    )

然后你可以编写如下代码:

//assume $a is your array, defined above
//and that you have used the id for the array key
$id = 51

do {
print $a['title'];
$id = $a['category_id'];
}while($id != 0);

编辑:array_multisort可能不是最干净的方法。

答案 1 :(得分:0)

尝试使用array_multisort()

答案 2 :(得分:0)

您的原始数组是否还包含要遗漏的条目?

如果没有,请使用:

$sort_array = array();
foreach ($original_array as $key => $value) {
    $sort_array[] = $value['category_id'];
}

array_multisort($sort_array, SORT_ASC, $original_array);

以上内容将根据category_id索引对$ original_array进行排序。

如果您的数组包含与其余部分无关的条目,并且您想要将它们遗漏,则必须使用以下内容:

// remap keys based on category_id
$parts = array();
foreach ($original_array as $array) {
    $parts[$array['category_id']] = $array;
}

// build tree list
$category_id = 0;
$result = array();
while (isset($parts[$category_id])) {
   $result[] = $parts[$category_id]['title'];
   $category_id = $parts[$category_id]['id'];
}

echo implode(' > ', $result);

答案 3 :(得分:0)

<?php

$array = Array(
    array('id' => 51, 'category_id' => 37, 'title' => 'Sims'),
    array('id' => 37, 'category_id' => 26, 'title' => 'Blackberry'),
    array('id' => 26, 'category_id' => 0, 'title' => 'Mobile Device'));

// First build an associative array ID->Object
$map = array();
foreach( $array as $value )
{
  $map[$value['id']] = $value;
}

// Then build your path
$path = array();
$value = $array[0];
while( true )
{
    $path[] = $value['title'];
    if( $value['category_id'] == 0 )
    {
        break;
    }
    $value = $map[$value['category_id']];
    if( !isset($value) )
    {
        die("Data Inconsistency");
    }
}


// Display path
echo implode(array_reverse($path), ' > ');

?>