我在多维数组中获取值时遇到问题
Array
(
[0] => Array
(
[name] => Brandow & Johnston, Inc.
[lat] => 34.051405
[lng] => -118.255576
)
[1] => Array
(
[name] => Industry Metrolink Train Station
[lat] => 34.00848564346
[lng] => -117.84509444967
)
[2] => Array
(
[name] => The Back Abbey
[lat] => 34.095161
[lng] => -117.720638
)
[3] => Array
(
[name] => Eureka! Burger Claremont
[lat] => 34.094572563643
[lng] => -117.72184828904
)
)
假设我上面有一个阵列
我正在使用foreach循环,如下面的
foreach($_SESSION['array'] as $value){
foreach($valueas $key_location=> $value_location){
if($key_location = "name"){$fsq_name = $value_location;}
$fsq_lat = $value_location["lat"];
$fsq_lng = $value_location["lng"];
echo "<i>".$fsq_lat."</i><br/>";
}
}
我尝试过使用if语句,或使用$value_location["lat"];
,但它没有生成正确的值。
如果我使用if($key_location === "lng"){$fsq_lng = $value_location;}
符号进行three equal
,则会在几次迭代时给出错误,然后生成lng
结果。如果我只是one equal
签名并回复它,它也会给我name
密钥。
我错过了什么吗?
由于
答案 0 :(得分:6)
您实际上并不需要内部foreach
循环。外部就足够了,因为它遍历数组。内部数组可以通过外部foreach
内的键访问。
foreach($_SESSION['array'] as $value){
$fsq_name = $value["name"];
$fsq_lat = $value["lat"];
$fsq_lng = $value["lng"];
echo "<i>".$fsq_lat."</i><br/>";
// Actually none of the above assignments are necessary
// you can just:
echo "<i>".$value["lat"]."</i><br/>";
}
答案 1 :(得分:0)
也许重构一下?
foreach($_SESSION['array'] as $value)
{
// pull the lat and lng values from the value
$fsq_lat = $value["lat"];
$fsq_lng = $value["lng"];
$fsq_name = $value["name"];
echo "<i>".$fsq_lat."</i><br/>";
}// foreach