在PHP中将平面数组转换为多维数组

时间:2017-11-11 09:01:02

标签: php arrays multidimensional-array

我正在尝试将平面数组转换为基于父母'的多维数组。并查看大量示例并获得良好结果,但有1个问题。我上次错过了数组。

首先我创建了一个平面阵列

$service_arr = array();
foreach( $order_info[0]['service'] as $ordered_service ) {
    $s_id       = $ordered_service['id'];
    $s_name     = $ordered_service['name'];
    $s_qty      = $ordered_service['qty'];
    $s_price    = $ordered_service['price'];
    $s_parent   = gp_get_item_parent( $s_id ); // return parent_id of the element.

    $service_arr[] = array(
        'id' => $s_id,
        'name' => $s_name,
        'qty' => $s_qty,
        'price' => $s_price,
        'parent' => $s_parent
    );
}

这回归是一个平面阵列

结果:

Array
(
    [0] => Array
        (
            [id] => 29
            [name] => Another Facial
            [qty] => 1
            [price] => 1800
            [parent] => 16
        )

    [1] => Array
        (
            [id] => 17
            [name] => Facial 1
            [qty] => 1
            [price] => 2000
            [parent] => 16
        )

    [2] => Array
        (
            [id] => 26
            [name] => Addon
            [qty] => 1
            [price] => 500
            [parent] => 17
        )

    [3] => Array
        (
            [id] => 39
            [name] => Another Addon
            [qty] => 1
            [price] => 150
            [parent] => 17
        )

    [4] => Array
        (
            [id] => 18
            [name] => Facial 2
            [qty] => 1
            [price] => 2000
            [parent] => 16
        )

    [5] => Array
        (
            [id] => 38
            [name] => Nice Facial
            [qty] => 1
            [price] => 3000
            [parent] => 16
        )

    [6] => Array
        (
            [id] => 21
            [name] => Massage 2
            [qty] => 1
            [price] => 6000
            [parent] => 14
        )

)

将平面转换为多维数组:

function create_tree_array( &$list, &$output, $parent_id ) {

    if ( ! is_array( $list ) ) {
        return;
    }

    if ( ! is_array( $output ) ) {
        return;
    }

    foreach( $list as $i => $item ) {
        if ( $item['parent'] == $parent_id )  {
            $item['addon'] = array();
            create_tree_array( $list, $item['addon'], $item['id'] );
            $output[] = $item;
        }
    }

}

并使用此功能

$services_tree = array();
create_tree_array( $service_arr, $services_tree, $service_arr[0]['parent'] );
  

它的工作但问题是它缺少数组的最后一项

[6] => Array (
          [id] => 21
          [name] => Massage 2
          [qty] => 1
          [price] => 6000
          [parent] => 14
)

0 个答案:

没有答案