在php中从现有数组创建一个新数组

时间:2014-09-28 14:10:12

标签: php arrays

我在基于现有数组创建新数组时遇到问题。我有以下数组,我想匹配元素' id'与父母'元件。如果值相同,那么我想创建另一个数组,其中子元素将在父元素下。

Array
(
    [0] => Array
        (
            [id] => 66
            [parent] => 26

        )

    [1] => Array
        (
            [id] => 47
            [parent] => 26

        )

    [2] => Array
        (
            [id] => 48           
            [parent] => 66

        )

我希望它是

Array
    (
        [0] => Array
            (
                [id] => 66
                [parent] => 26

            ) 
             [0] => Array 
             (  

                      [id] => 48
                      [parent] => 66


             )

        [1] => Array
            (
                [id] => 47
                [parent] => 26

            )

我坚持使用以下代码。我已经获得了值,但我不知道如何匹配数组中的其他元素。

foreach($firstlevel_results as $k => $v)
{
     echo $v['id']."==".$v['parent']."==".$v['grandparent']."<br>";
}

如果有任何可行的方法,请建议。

1 个答案:

答案 0 :(得分:0)

尽管代码很长很容易。基本上,这个想法应该是它:

$my_array = Array(
    Array ('id' => 66, 'parent' => 26, 'grandparent' => 18), 
    Array ('id' => 23, 'parent' => 66, 'grandparent' => 57),
    Array ('id' => 47, 'parent' => 26, 'grandparent' => 18),
    Array ('id' => 48, 'parent' => 66, 'grandparent' => 26),
    Array ('id' => 11, 'parent' => 66, 'grandparent' => 89),
    Array ('id' => 200, 'parent' => 98, 'grandparent' => 26) 
);

function merge($target_id, $target_array) {
    #1) Find subarray with ID == $target_id
    $new = array();
    # fast path (better than array_filter)
    foreach ($target_array as $key => $sub_array) {
        #find array with id == $target_id
        if ($sub_array['id'] === $target_id) {
            # first index will be super group
            $new[0] = array($sub_array);
            # removing it...
            unset($target_array[$key]);
            # it's not need continue anymore...
            break;
        }
    }

    # 2)  and now gonna compare ids with targert_id
    foreach ($target_array as $index => $sub_array) {

        if ($sub_array['parent'] == $target_id) {
            # index 0 is the super group as said early...
            array_push($new[0], $sub_array);

        } else {
            # only push but not groups
            array_push($new, $sub_array);
        }
    }

    return $new;
}


print_r(merge(66, $my_array));

当然,这段代码中有些内容可以改进,但这就是想法。