如下所示:
Array
(
[0] => stdClass Object
(
[city_id] => 2222
[city_name] => newCity
)
[1] => stdClass Object
(
[city_id] => 4444
[city_name] => oldCity
)
[2] => stdClass Object
(
[city_id] => 6666
[city_name] => newCity2
)
)
现在,我想在设置city_id
时获取city_name
,如何在我的代码中获取它?
例如,如果我为newCity2
设置了city_name
,那么我会看到6666
等city_id
。
答案 0 :(得分:0)
你需要以
的形式循环播放它foreach($data as $key=>$val){
echo 'City ID ::'.$val->city_id."<br />";
echo 'City Name ::'.$val->city_name."<br />";
}
如果您想查看特定数据,则可以将上面的内容修改为
foreach($data as $key=>$val){
if($val->city_name == 'newCity2'){
echo 'City ID ::'.$val->city_id."<br />";
break;
}
}
function getCityIDByName($cityname,$data){
$return = '';
foreach($data as $key=>$val){
if($val->city_name == $cityname){
$return = $val->city_id
break;
}
}
return $return ;
}
$city_id = getCityIDByName ('newCity2',$data);
答案 1 :(得分:0)
您必须遍历数组并检查city_name
以获取相应的ID。您最初也可以这样设置一个数组,其中city_name
为关键字,city_id
为数值。
foreach ($array as $value) {
if ($value->city_name == $compareCityName) {
$city_id = $value->city_id;
}
}