将值插入多维数组,但只插入1

时间:2016-02-12 03:14:04

标签: php arrays multidimensional-array

我有这个数组:

$order_list = array ( array ("tangible", 1, 8, 1, 19000),
                      array ("tangible", 6, 2, 10, NULL),
                      array ("tangible", 1, 17, 1, 28000));

我希望将此作为输出:

Array
(
    [1] => Array       //$order_list[1]
        (
            [0] => 8   //$order_list[2]
            [1] => 17  //$order_list[2]
        )

    [6] => Array       //$order_list[1]
        (
            [0] => 2   //$order_list[2]
        )

)

这是我的代码:

$order_array = array ();

foreach ($order_list as $value) {

    $vendor_id = $value[1];
    $product_id = array($value[2]);
    $order_array[$vendor_id] = $product_id;

}

echo '<pre>';
print_r($order_array);

这只产生:

    [1] => Array
        (
            [0] => 8
        )

如何拥有:

    [1] => Array
        (
            [0] => 8
            [1] => 17 //second value inserted into same array
        )

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:2)

无需将其他值转换为另一个单独的数组。只需正常推送它们,一个用作密钥(在本例中为$vendor_id),然后另一个用作推送的另一个正常值(在这种情况下仅$product_id而不是array($value[2])):

foreach ($order_list as $value) {

    $vendor_id = $value[1];
    $product_id = $value[2]; // just that single element, no need to assign it into another container
    $order_array[$vendor_id][] = $product_id;
    // use as key   ^        ^ then just push it

}

通过这样做:

$order_array[$vendor_id] = $product_id;

这将覆盖该密钥对值,而不是不断地推送其中的元素。

相关问题