2014-04-27 46 views
0

有無陣列象下面這樣:如何從stdClass的對象數組re​​trive價值

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,如果你想看到一個特定的數據,那麼你通過它等

+1

http://stackoverflow.com/questions/5156841/stdclass-object-and-array-how-to-using-php?rq=1 ..也許這個? – briosheje

回答

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); 
+0

city_name的值不是靜態的,它是動態的 – sIiiS

+0

好吧,您可以在我更新問題時創建一個函數來執行此操作。 –

+0

請參閱我的談話在另一個答案@Explosion丸,兩個答案都一樣,但沒有爲我工作:( – sIiiS

0

您將不得不迭代數組並檢查city_name獲取相應的ID。您最初也可以這樣做,以設置一個數組,其中city_name作爲鍵,city_id作爲值。

foreach ($array as $value) { 
    if ($value->city_name == $compareCityName) { 
     $city_id = $value->city_id; 
    } 
} 
+0

我沒設置喜歡你,但是當我想看到的結果,那麼得到的錯誤'未定義的變量:cityId',我代碼是:'$城市= 'Oldcity酒店';的foreach($結果$值){$的cityName = $值 - > CITY_NAME; 如果($的cityName == $地點){$ cityId = $值 - > city_id;} }的var_dump($ cityId);退出;' – sIiiS

+0

@sIiiS這意味着沒有名爲'城市oldCity'發現 –

+0

我之前'$城市=「Oldcity酒店」設置;'你可以在我的代碼看,但爲什麼沒有找到它? – sIiiS