获取子数组键php

时间:2012-06-13 00:05:00

标签: php arrays foreach

我有一个数组:

Array
( 
[47] => Array
    (
        [name] => 3543 good
        [price] => 100.0000
        [image] => data/hp_1.jpg
        [discount] => 
        [stock_status] => 
        [weight_class] => kg
    )

[28] => Array
    (
        [name] => HTC Touch HD
        [price] => 100.0000
        [image] => data/htc_touch_hd_1.jpg
        [discount] => 
        [stock_status] => 
        [weight_class] => g
    )

[41] => Array
    (
        [name] => iMac
        [price] => 100.0000
        [image] => data/imac_1.jpg
        [discount] => 
        [stock_status] => 
        [weight_class] => kg
    )

[40] => Array
    (
        [name] => iPhone
        [price] => 101.0000
        [image] => data/iphone_1.jpg
        [discount] => 
        [stock_status] => 
        [weight_class] => kg
    )
)

我需要子数组键(47,28等),因为它是我的产品ID

我正在运行foreach循环以获取详细信息并分配给新数组,例如'name' => $result['name']但无法弄清楚如何定位产品ID。

4 个答案:

答案 0 :(得分:2)

您可以将键指定给foreach循环中的变量:

foreach($array as $id => $result) {
    $item = array('name' => $result['name'], 'id' => $id);
}

答案 1 :(得分:1)

将其作为具有键值对的关联数组进行迭代。

foreach($array as $key=>$value) {
   echo $key; // this is what you need, if I got you right
}

答案 2 :(得分:1)

foreach允许您以这种方式迭代值而不是迭代键:

foreach($items as $key => $value)
{
    ...
}

在你的情况下,它看起来像:

foreach($results as $id => $result)
{
    $item = array('name' => $result['name'], 'id' => $id, ...);
}

答案 3 :(得分:0)

将关键变量添加到foreach循环中,如下所示:

foreach( $array as $product_id => $result)
    echo $product_id . ' costs ' . $result['price'] . "\n";