Foreach loop array and stdclass object, getting values - php

I'm trying to get to a certain value using foreach (which I believe is the best way, performance-wise, as of know of)
[businesses] => Array
(
[0] => stdClass Object
(
[rating] => 4
[location] => stdClass Object
(
[city] => Claremont
[display_address] => Array
(
[0] => 580 W First St
[1] => Claremont, CA 91711
)
[geo_accuracy] => 8
[postal_code] => 91711
[country_code] => US
[address] => Array
(
[0] => 580 W First St
)
[coordinate] => stdClass Object
(
[latitude] => 34.094112
[longitude] => -117.7250746
)
)
)
)
I'm trying to get latitude and longitude. But keep in mind that I will have more than just [0] => stdClass Object. There will be multiple numbers. I know I can do something like $response->businesses[0]->location or some sort, but that only gets the 0 key, I need to be able to foreach the keys to get it.
Can someone help me do a foreach on this?
for example I'm doing this so far...
foreach($response->businesses->location as $llk=>$coordinate){
if($llk === "coordinate"){
$selected_lat = $coordinate->latitude;
$selected_lng = $coordinate->longitude;
}
}
So far its giving me errors.
Thanks!

The following might be just what you are looking for:
foreach($response->businesses as $business) {
if(!empty($business->location->coordinate)) {
$coord = $business->location->coordinate;
$selected_lat = $coord->latitude;
$selected_long = $coord->longitude;
}
}

Try this:
foreach ($response->businesses as $business) {
$selected_lat = $business->location->coordinate->latitude;
$selected_lng = $business->location->coordinate->longitude;
}

You probably don't need a foreach loop for this, just use simple array iteration to go through the top level stdClass objects, then just use dereferencing to get each longitude/latitude pair.
for($i = 0; $i < count($response->businesses); $i++)
{
$coords = $response->businesses[$i]->location->coordinate;
$long = $coords->longitude;
$lat = $coords->latitude;
}
That should work as far as I can tell.

Related

Problems changing values in an array/object nested combination array

I don't know what to do to get this done what would like to do. I tried multiple approaches, e.g. I used array_map, array_walk, nested foreach loops with get_object_vars and I worked with json_decode/encode and so on. I always come a little bit further but never reach my goal and I would like to get some guidance from you
Basically when you see the array below, how would you proceed when you want to change some value in the path array for multiple values in the array itself?
My questions:
1) Is it right that I must convert both nested objects to an array first or is this not nesessary to do this? I mean I always get some type conversion error which tells me that I either have everything as an object or array. Is this right?
2) If this mistery is solved, which php array function is the appropriate one to change values in an array(/object)? As I have written above, I tried so many and I don't see the trees in the woods anymore. Which one do you suggest to me to use in a foreach loop?
Array
(
[0] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Bob
[1] => pictures
[2] => food
)
)
)
[1] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Alice
[1] => pictures
[2] => vacations
[3] => rome
)
)
)
)
I would suggest that,
you create an array with keys as new path and value as old path (
path to be replaced).
Loop you path array and check if it is available in above defined array.
If available replace it with key of above defined array.
For example
// array defined as point 1
$change_path_array= array('pics'=>'pictures','meal'=>'food');
// $array is your array.
foreach ($array as $value) {
// loop you path array
for($i=0;$i<count($value->doc->path);$i++){
// check if the value is in defined array
if(in_array($value->doc->path[$i],$change_path_array)){
// get the key and replace it.
$value->doc->path[$i] = array_search($value->doc->path[$i], $change_path_array);
}
}
}
Out Put: picture is replaced with pics and food with meal
Array
(
[0] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Bob
[1] => pics
[2] => meal
)
)
)
[1] => stdClass Object
(
[doc] => stdClass Object
(
[path] => Array
(
[0] => Alice
[1] => pics
[2] => vacations
[3] => rome
)
)
)
)
You can modify the code to check casesensitive.
Example of changing all pictures to photos:
$doc1 = new \stdClass;
$doc1->doc = new \stdClass;
$doc1->doc->path = array('Bob', 'pictures', 'food');
$doc2 = new \stdClass;
$doc2->doc = new \stdClass;
$doc2->doc->path = array('Alice', 'pictures', 'vacations', 'rome');
$documents = array($doc1, $doc2);
/* change all 'pictures' to 'photos' */
foreach ($documents as &$doc) {
foreach ($doc->doc->path as &$element) {
if ($element == 'pictures') {
$element = 'photos';
}
unset($element);
}
unset($doc);
}
print_r($documents);
You can do it like this:
for($i = 0; $i < count($arr); $i++){
$path_array = $arr[$i]->doc->path;
// do your modifications for [i]th path element
// in your case replace all 'Bob's with 'Joe's
$path_array = array_map(function($paths){
if($paths == 'Bob') return 'Joe';
return $paths;
}, $paths_array);
$arr[$i]->doc->path = $path_array;
}

Extracting a property from an array of an array of objects

I've got an object, containing an array of objects, containing an array of values:
stdClass Object (
[devices] => Array (
[0] => stdClass Object (
[location] => 1
[delegate] =>
[type] => 1
[id] => 1234
[IP] => 1.2.3.4
[name] => host1
[owner] => user6
[security] => 15
)
[1] => stdClass Object (
[location] => 2
[delegate] =>
[type] => 1
[id] => 4321
[IP] => 4.3.2.1
[name] => host2
[owner] => user9
[security] => 15
)
)
)
I want to extract just the id and name into an array in the form of:
$devices['id'] = $name;
I considered using the array_map() function, but couldn't work out how to use it... Any ideas?
This will generate you a new array like I think you want
I know you says that delegate is an object but the print does not show it that way
$new = array();
foreach($obj->devices as $device) {
$new[][$device->id] = $device->name;
}
Would something like this not work? Untested but it cycles through the object structure to extract what I think you need.
$devices = myfunction($my_object);
function myfunction($ob){
$devices = array();
if(isset($ob->devices)){
foreach($ob->devices as $d){
if(isset($d->delegate->name && isset($d->delegate->id))){
$devices[$d->delegate->id] = $d->delegate->name;
}
}
}
return($devices);
}
Im usually using this function to generate all child and parent array stdclass / object, but still make key same :
function GenNewArr($arr=array()){
$newarr = array();
foreach($arr as $a=>$b){
$newarr[$a] = is_object($b) || is_array($b) ? GenNewArr($b) : $b ;
}
return $newarr;
}

sort mysql rows by column?

I have following sql query:
SELECT job_id, job_type FROM jobs
I'm getting the following result (set of rows) from mysql query:
RESULT (print_r):
Array
(
[0] => stdClass Object
(
[job_id] => 239
[job_type] => 'type1';
}
[1] => stdClass Object
{
[job_id] => 53
[job_type] => 'type2';
}
[2] => stdClass Object
{
[job_id] => 76
[job_type] => 'type3';
}
[3] => stdClass Object
{
[job_id] => 78
[job_type] => 'type1';
}
)
As you can see I've got three types of job: type1, type2, type3
Is there any way to map/regroup these results by job_type?
Basically I'd like to have something similar to this:
Array
(
['type1'] => Array (
[0] => stdClass Object
{
[job_id] => 239
[job_type] => 'type1';
}
[1] => stdClass Object
{
[job_id] => 76
[job_type] => 'type1';
}
)
['type2'] => Array (
[0] => stdClass Object
{
[job_id] => 53
[job_type] => 'type2';
}
)
['type3'] => Array (
[0] => stdClass Object
{
[job_id] => 78
[job_type] => 'type3';
}
)
)
Or maybe I should use different query?
I've tried to use array_map() with no luck, but I was getting only one array with elements from only one job_type.
Thanks in advance.
You cannot do this with predefined PHP functions. But you can do it yourself pretty easily.
For example: Assuming you have your MySQL result as written in your question in a variable called $rows, you can do the following to get the desired map.
$map = array();
foreach($rows as $row) {
if (!isset($map[$row->job_type])) {
$map[$row->job_type] = array($row);
} else {
$map[$row->job_type][] = $row;
}
}
Now $map contains your desired array.
Unfortunately for this task does not have a native solution in pure PHP/MySQL. So You need to sort it on PHP side manualy. I think You should write function for this an use it when You need
function sortBy($array, $key, $sortKeys=false){
// I don't test this function, just write it for answer, so it may contain errors
$tmp = array();
foreach($array as $k=>$v){
$tmp[$array[$k][$key]][] = $v;
}
if($sortKeys)
ksort($tmp);
return $tmp;
}
And use it like
print_r(sortBy(mySQLSelect(),'job_type'));

php foreach loop multidimensional array having issues

I'm having problems getting values in my multidimensional arrays
Array
(
[0] => Array
(
[name] => Brandow & Johnston, Inc.
[lat] => 34.051405
[lng] => -118.255576
)
[1] => Array
(
[name] => Industry Metrolink Train Station
[lat] => 34.00848564346
[lng] => -117.84509444967
)
[2] => Array
(
[name] => The Back Abbey
[lat] => 34.095161
[lng] => -117.720638
)
[3] => Array
(
[name] => Eureka! Burger Claremont
[lat] => 34.094572563643
[lng] => -117.72184828904
)
)
Lets say I have an array such above
And I'm using a foreach loop such as below
foreach($_SESSION['array'] as $value){
foreach($valueas $key_location=> $value_location){
if($key_location = "name"){$fsq_name = $value_location;}
$fsq_lat = $value_location["lat"];
$fsq_lng = $value_location["lng"];
echo "<i>".$fsq_lat."</i><br/>";
}
}
I've tried using the if statement, or using $value_location["lat"]; but its not producing the correct values.
If I do if($key_location === "lng"){$fsq_lng = $value_location;} with three equal signs, it'll give me errors for a few iterations and then produce the lng results. if I just do one equal sign and echo it out, it'll give me the name key as well.
Am I missing something?
Thanks
You don't actually need the inner foreach loop. The outer one is sufficient, since it iterates over arrays. The inner arrays can be accessed by key inside the outer foreach.
foreach($_SESSION['array'] as $value){
$fsq_name = $value["name"];
$fsq_lat = $value["lat"];
$fsq_lng = $value["lng"];
echo "<i>".$fsq_lat."</i><br/>";
// Actually none of the above assignments are necessary
// you can just:
echo "<i>".$value["lat"]."</i><br/>";
}
Maybe refactor a bit?
foreach($_SESSION['array'] as $value)
{
// pull the lat and lng values from the value
$fsq_lat = $value["lat"];
$fsq_lng = $value["lng"];
$fsq_name = $value["name"];
echo "<i>".$fsq_lat."</i><br/>";
}// foreach

Multi dimensional array, with an object for good measure - iteration?

This one is starting to get on my nerves. Still fairly new to arrays and objects.
I need to be able to pull out [id] in the numbered array, plus get access to the lonely snippet_count at the end.
I can do it if there is no top level container array using a foreach $a as $k => $v., (from an earlier SO question) but am struggling a level deeper. Thanks.
Array
(
[snippets] => Array
(
[0] => stdClass Object
(
[id] => 123456789
)
[1] => stdClass Object
(
[id] => 123456789
)
[2] => stdClass Object
(
[id] => 123456789
)
//and so on
)
[snippet_count] => 500
)
You can iterate over just the snippets array to get the IDs
$ids = array();
foreach ($array['snippets'] as $snippet) {
$ids[] = $snippet->id;
}
$count = $array['snippet_count'];
Is this what you're looking for?

Categories