1

我有一个数组:

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

4 回答 4

2

您可以将键分配给 foreach 循环中的变量:

foreach($array as $id => $result) {
    $item = array('name' => $result['name'], 'id' => $id);
}
于 2012-06-13T00:07:26.890 回答
1

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

foreach($array as $key=>$value) {
   echo $key; // this is what you need, if I got you right
}
于 2012-06-13T00:07:14.950 回答
1

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

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

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

foreach($results as $id => $result)
{
    $item = array('name' => $result['name'], 'id' => $id, ...);
}
于 2012-06-13T00:13:29.693 回答
0

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

foreach( $array as $product_id => $result)
    echo $product_id . ' costs ' . $result['price'] . "\n";
于 2012-06-13T00:07:13.110 回答