从数组提取数据的PHP选项? [英] PHP options for extracting data from an array?

查看:90
本文介绍了从数组提取数据的PHP选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此二维数组,每个元素都有两个索引-行和列.

Given this two-dimensional array, each element has two indexes – row and column.

<?php
$shop = array( array("rose", 1.25 , 15),
               array("daisy", 0.75 , 25),
               array("orchid", 1.15 , 7) 
             ); 
?>

这是我仅有的两个使用行和列索引从数组中提取数据的选项吗?

Are these my only two options for extracting the data from the array, using row and column indexes?

<?php
echo "<h1>Manual access to each element</h1>";

echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2]."<br />";
echo $shop[1][0]." costs ".$shop[1][1]." and you get ".$shop[1][2]."<br />";
echo $shop[2][0]." costs ".$shop[2][1]." and you get ".$shop[2][2]."<br />";

echo "<h1>Using loops to display array elements</h1>";

echo "<ol>";
for ($row = 0; $row < 3; $row++)
{
    echo "<li><b>The row number $row</b>";
    echo "<ul>";

    for ($col = 0; $col < 3; $col++)
    {
        echo "<li>".$shop[$row][$col]."</li>";
    }

    echo "</ul>";
    echo "</li>";
}
echo "</ol>";
?>

推荐答案

foreach($shop as $items){
 echo $items[0]." costs ".$items[1]." and you get ".$items[2]."<br />";
}

foreach对我来说似乎更简单,而且如果您的密钥不是数字之类的,它将可以处理

foreach seems more simple for me, plus it would handle if your key are not numeric like

array(         'foo' => array("rose", 1.25 , 15),
               'bar' => array("daisy", 0.75 , 25),
               'foobar' =>array("orchid", 1.15 , 7) 
             );

我个人避免在PHP中使用for,因为在大多数情况下,它不如foreach灵活.

personally I avoid to use for in PHP because it's less flexible then foreach in most case.

这篇关于从数组提取数据的PHP选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆