I have a response in below format. I am using laravel.
I want to check if there is street_number present or not despite of their index
and if yes just print the long_name
similar I want to check if there is route
in types
of this array or not. if yes print route long_name
and so on.
dd($dataArray);
gives this response
array:3 [
"html_attributions" => []
"result" => array:15 [
"address_components" => array:7 [
0 => array:3 [
"long_name" => "19"
"short_name" => "19"
"types" => array:1 [
0 => "street_number"
]
]
1 => array:3 [
"long_name" => "Becket Street South"
"short_name" => "Becket St S"
"types" => array:1 [
0 => "route"
]
]
2 => array:3 [
"long_name" => "senroy"
"short_name" => "Slenroy"
"types" => array:2 [
0 => "locality"
1 => "political"
]
]
]
I am looping like this
$newArray=[];
foreach($dataArray['result'] as $data){
// check if street_number in array or not if yes push it value to new array
//same for other types as well
}
CodePudding user response:
the inside of your foreach is problematic: should be like this:
foreach($dataArray as $key=> $data){
if (in_array('street_number',$data['types'])) {
}
}
because your types is already in $data inside the foreach. So you don't need to say $key again.
Edit 1:
found the problem. remove isset($data[$key])
because it is always false. because the $key is returning 0,1,.... but $data keys are these three : 'long_name' , 'short_name' , 'types' . You can check by dd($key)
Edit 2: After your latest update of the question, your foreach should be like this:
foreach($dataArray['result']['address_components'] as $data){
if (in_array('street_number',$data['types'])) {
dd('should be here');
}
}
CodePudding user response:
May this can help you
foreach ($data['result']['address_components'] as $val) {
if(\Illuminate\Support\Arr::has($val, 'types') && in_array('street_number', $val['types'])) {
echo "For Street Nu.";
}else if(\Illuminate\Support\Arr::has($val, 'types') && in_array('route', $val['types'])) {
echo "For Route";
}
}