如何从数组中的stdClass对象中检索值

时间:2014-04-27 22:06:05

标签: php arrays object stdclass

如下所示:

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,那么我会看到6666city_id

2 个答案:

答案 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;
    }
}