0

Have array like below :

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

    )
)

Now, I want get city_id when I set city_name, how can I get it in my codes?

For example, If I set newCity2 for city_name then I see 6666 for city_id and etc.

1

2 Answers 2

0

You would have to iterate over the array and check city_name to get the corresponding ID. You could also do this initially to set up an array with city_name as the key and city_id as the value.

foreach ($array as $value) {
    if ($value->city_name == $compareCityName) {
        $city_id = $value->city_id;
    }
}
Sign up to request clarification or add additional context in comments.

10 Comments

I did set like you but when I want to see result then got error Undefined variable: cityId, my code is : $city = 'oldCity'; foreach($results as $value){ $cityName = $value->city_name; if ($cityName == $city) { $cityId = $value->city_id; } } var_dump ($cityId); exit;
@sIiiS that means that no city named oldCity was found
I did set before $city = 'oldCity'; as you can see in my codes, but why can not find it?
@sIiiS because it's not there? Depends on the contents of $results
value of $results is same as $array not else, and in the $results in my main Q, oldCity is available
|
0

You need to loop through it as

foreach($data as $key=>$val){
  echo 'City ID ::'.$val->city_id."<br />";
  echo 'City Name ::'.$val->city_name."<br />";
}

If you want to see a particular data then you can modify above as

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

3 Comments

the value of city_name is not static, it is dynamic
well you can make a function to do so as I updated in the question.
please see my conversation with @Explosion Pills in the another answer, both answers are same but do not work for me :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.