使用 PHP 在多维数组及其子数组中循环

我有以下数组:


$items = array(

    array(

        'name' => 'Item 1',

        'desc' => 'Lorem ipsum...',

        'rates' => array(

            'Yes' => 50,

            'No' => 75

        )

    ),

    array(

        'name' => 'Item 2',

        'desc' => 'Lorem ipsum...',

        'rates' => array(

            'Yes' => 50,

            'No' => 0

        )

    )

);

我怎样才能在 之间循环rates?


这是我尝试过的:


foreach ($items as $item) {

    foreach($item['rates'] as $rate => $value){

        echo $rate['rates'];

    }

}

谢谢。


GCT1015
浏览 159回答 3
3回答

米琪卡哇伊

将您的代码更改为foreach ($items as $item) {&nbsp; foreach($item['rates'] as $rate => $value){&nbsp; &nbsp; echo $value;echo '<br/>';&nbsp;}}在第二个循环中$rate是键并$value具有该键的当前值。

青春有我

要保留(并继续)您的工作:foreach ($items as $item) {&nbsp; echo "Number of ratings for item: {$item['name']}<br/>";&nbsp; foreach($item['rates'] as $rateKey => $rateValue) {&nbsp; &nbsp; echo " - {$rateKey}: {$rateValue}<br/>";&nbsp; }}输出:Number of ratings for item: Item 1- Yes: 50- No: 75Number of ratings for item: Item 2- Yes: 50- No: 0

长风秋雁

循环内循环比循环慢得多,而且只有当您循环的数组变大时,它才会变得明显。因此,您可以采取的一种方法如下:&nbsp; &nbsp; $items = array(&nbsp; &nbsp; array(&nbsp; &nbsp; &nbsp; &nbsp; 'name' => 'Item 1',&nbsp; &nbsp; &nbsp; &nbsp; 'desc' => 'Lorem ipsum text',&nbsp; &nbsp; &nbsp; &nbsp; 'rates' => array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Yes' => 50,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'No' => 75&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; ),&nbsp; &nbsp; array(&nbsp; &nbsp; &nbsp; &nbsp; 'name' => 'Item 2',&nbsp; &nbsp; &nbsp; &nbsp; 'desc' => 'Lorem ipsum text',&nbsp; &nbsp; &nbsp; &nbsp; 'rates' => array(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'Yes' => 50,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'No' => 0&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp;)&nbsp; &nbsp; );$rates = array_column($items, 'rates');foreach($rates as $key => $value) {&nbsp; &nbsp; if($value['Yes']) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;echo " Yes: {$value['Yes']}<br/>";&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;echo " No: {$value['No']}<br/><br/>";}结果:Yes: 50No: 75Yes: 50No: 0
打开App,查看更多内容
随时随地看视频慕课网APP