php中的foreach删除了密钥

时间:2015-10-15 17:56:11

标签: php

我将此代码用于循环:

<?php foreach($_SESSION['accessories'] as $accessory) : ?>

    <?php var_dump($accessory); ?>

<?php endforeach; ?>

问题是,现在我可以访问每个附件的内容,但不知道该附件的ID,因为原始数组看起来像这样:

[accessories] => Array
    (
        [63] => Array
            (
                [price] => 15000
                [name] => Product 2
            )

        .
        ..
        ...

    )

63失去了;(

任何想法如何获得63?

2 个答案:

答案 0 :(得分:1)

您需要在foreach循环中添加$ key

<?php foreach($_SESSION['accessories'] as $key => $accessory) : ?> 
<?php var_dump($accessory); ?> 
<?php endforeach; ?>

这将给出你正在寻找的关键63 ..

答案 1 :(得分:1)

<?php foreach($_SESSION['accessories'] as $key => $accessory) : 

    echo $key;                 // prints id 63
    echo $accessory['price'];  // prints price
    echo $accessory['name'];   // prints names 

   endforeach; ?>