PHP options for extracting data from an array?
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]开发者_JAVA百科." 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 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)
);
personally I avoid to use for
in PHP because it's less flexible then foreach
in most case.
You could also use
foreach($shop as $shoprow)
精彩评论