如何获得数组的价值,但没有索引

时间:2016-02-12 07:37:33

标签: php arrays

我有这个数组:

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

我希望根据product_id ($order_list[2])vendor_id ($order_list[1])组合在一起,然后我就这样做了。它看起来像这样:

Array
(
    [1] => Array
        (
            [0] => Array
                (
                    [product_id] => 8
                    [pcs] => 1
                    [weight] => 115.00
                )

            [1] => Array
                (
                    [product_id] => 17
                    [pcs] => 1
                    [weight] => 120.00
                )

        )

    [6] => Array
        (
            [0] => Array
                (
                    [product_id] => 2
                    [pcs] => 10
                    [weight] => 250.00
                )

        )

)

现在问题是......

如果这个新数组的索引包含vendor_id,如何获取这个新数组的值?

我期待分别为$new_array[0]$new_array[1]的1或6。所以我可以创建for循环。它还有可能吗?谢谢。

更新:我有这个代码获取值:

foreach ($order_array as $value) {
    echo '<pre>';
    print_r($value);
}

但是,不幸的是我得到了这个结果:

Array
(
    [0] => Array
        (
            [product_id] => 8
            [pcs] => 1
            [weight] => 115.00
        )

    [1] => Array
        (
            [product_id] => 17
            [pcs] => 1
            [weight] => 120.00
        )

)
Array
(
    [0] => Array
        (
            [product_id] => 2
            [pcs] => 10
            [weight] => 250.00
        )

)

我仍然无法获得16: - (

1 个答案:

答案 0 :(得分:2)

在foreach循环中添加关键字段:

$order_list = Array
(
    1 => Array
    (
        0 => Array
        (
            'product_id' => 8,
            'pcs' => 1,
            'weight' => 115.00
        ),

        1 => Array
        (
            'product_id' => 17,
            'pcs' => 1,
            'weight' => 120.00
        )

    ),

    6 => Array
    (
        0 => Array
        (
            'product_id' => 2,
            'pcs' => 10,
            'weight' => 250.00
        )

    )

);

foreach ($order_list as $vendor_id => $value) {
    echo '<pre>';
    echo "Vendor Id: " . $vendor_id . '<br />';
    print_r($value);
}

<强>输出:

Vendor Id: 1
Array
(
    [0] => Array
        (
            [product_id] => 8
            [pcs] => 1
            [weight] => 115
        )

    [1] => Array
        (
            [product_id] => 17
            [pcs] => 1
            [weight] => 120
        )

)
Vendor Id: 6
Array
(
    [0] => Array
        (
            [product_id] => 2
            [pcs] => 10
            [weight] => 250
        )

)