how to get data into an array? - php

I saved the result of a CURL expression into variable $data. When I print this value using print_r($data), It gives me like that
stdClass Object
(
[zip_codes] => Array
(
[0] => stdClass Object
(
[zip_code] => 10015
[distance] => 0.521
)
[1] => stdClass Object
(
[zip_code] => 10079
[distance] => 0.521
)
[2] => stdClass Object
(
[zip_code] => 10094
[distance] => 0.521
)
I want only zip_code into an array, Please help me how do I get only zip_code into an array.
Thanks

So use array_map():
$result = array_map(function($x)
{
return $x->zip_code
}, $obj->zip_codes);

Try something like :
foreach($data->zip_codes as $zipObj)
{
echo $zipObj->zip_code;
}
This will loop over the zip codes array and output the relevant value.

Try something like this:
First iterate trought the collection of objects an get the zip code property and add it to an array
<?php
$result = array();
$zipCodes = $data->zip_codes;
for($i = 0; $i < sizeOf($zipCodes); $i++){
$result[] = $zipCodes->zip_code;
}
?>

You can use array_map, this function allows you to apply a callback to the array.
$zip_codes = array_map(function($i) { return $i->zip_code; }, $data->zip_codes);

Related

php removing an element from objects

So, I have following db result:
Array
(
[0] => stdClass Object
(
[id] => 1
[user] => 1
[img] => 2016/02/img_8488.jpg
[url] => /p=?44
[sent_date] => 2016-02-13 00:00:00
)
[1] => stdClass Object
(
[id] => 2
[user] => 185
[img] =>
[url] => /?p=54
[sent_date] => 2016-02-06 00:00:00
)
)
How would I remove [id] and [sent_date] from the query result?
I am not sure if I am using unset right.
unset($results[0]['id']);
$reindex = array_values($results);
$objectarray = $reindex;
Instead of removal or unset you can create a new array;
$i = 0;
$newResult = array();
foreach($result as $value){
$newResult[$i]["user"] = $value->user;
$newResult[$i]["img"] = $value->img;
$newResult[$i]["url"] = $value->url;
$i++;
}
print_r($newResult);
$newResult will return the new array and your original array remains same you can use it if you need.
Or removal of indexes is must required than use unset inside the foreach loop as:
unset($value->id);
unset($value->sent_date);
Side note:
Also keep in mind you can not use it as $value["id"] becuase its a property not an array index.
Use unset($results[0]->id); and unset($results[0]->sent_date) instead and it should work. If you want to do this in all of the array objects:
for($i = 0; $i<sizeof($results); $i++)
{
unset($results[$i]->id);
unset($results[$i]->sent_date);
}

How can I put JSON to MySQL with PHP loop?

I have JSON like this (from nested sorting)
[
{"id":13},{"id":14},
{"id":15,
"children":[
{"id":16},{"id":17},{"id":18}
]
},
{"id":19},{"id":20},
{"id":21,
"children":[
{"id":22}
]
}
]
how I PHP loop to put this JSON in MySQL
Thank you.
As with any valid JSON format string, you can use PHP's built-in json_decode to convert it into a parsable object and then loop through those parameters. In this case, from the JSON string you've given (which seems to be an array)
$array = json_decode($string);
foreach ($array as $val) {
//The object $val will be:
"id":13
}
If it's nested, you would do another foreach loop and detect for the property that needs to be looped. For example you could do this in a variety of ways (check for the "children" property, loop through the $val properties and check if it is an array, if it is then loop through that). Inside this foreach loop iteration, you can insert it, or do execute whatever statement you need to get it inside MySQL
Your question is pretty vague on the format and way you want it inserted. I'd suggest showing some code you've tried so other people can help you and know what direction you're going in. (that's probably the reason for the downvote, not mine by the way)
Looping through all the properties of object php
just put your valid json inside json_decode and assign it to a php array as below
//$php_arr = json_decode('YOUR_JSON');
$php_arr = json_decode('[{"id":13},{"id":14},{"id":15,"children":[{"id":16},{"id":17},{"id":18}]},{"id":19},{"id":20},{"id":21,"children":[{"id":22}]}]');
/*comment the following 3 lines when done*/
echo "<pre>";
print_r($php_arr);
echo "</pre>";
/*comment the above 3 lines when done*/
output
Array
(
[0] => stdClass Object
(
[id] => 13
)
[1] => stdClass Object
(
[id] => 14
)
[2] => stdClass Object
(
[id] => 15
[children] => Array
(
[0] => stdClass Object
(
[id] => 16
)
[1] => stdClass Object
(
[id] => 17
)
[2] => stdClass Object
(
[id] => 18
)
)
)
[3] => stdClass Object
(
[id] => 19
)
[4] => stdClass Object
(
[id] => 20
)
[5] => stdClass Object
(
[id] => 21
[children] => Array
(
[0] => stdClass Object
(
[id] => 22
)
)
)
)
Now as you have PHP array do what ever you want like
foreach($php_arr as $arr){
if(!isset($arr['children'])){
$q = "insert into tbl(id) values('".$arr['id']."')";
}else{
//your logic
}
}
You need to use json_decode function to decode JSON data. Then use foreach loop to manipulate data.
Try example
$str = '
[{"id":13},{"id":14},{"id":15,"children":[{"id":16},{"id":17},{"id":18}]},{"id":19},{"id":20},{"id":21,"children":[{"id":22}]}]
';
$json = json_decode($str);
//var_dump($json);
foreach ($json as $item)
{
//The object $val will be:
echo $item->id."<br />";
//You INSERT query is here
//echo "INSERT INTO table (field) VALUE ($item->id)";
$query = mysqli_query($conn, "INSERT INTO table (field) VALUE ($val->id)");
}

Anonymous PHP function with in_array not working

I have this simple array $tree in PHP that I need to filter based on an array of tags matching those in the array.
Array
(
[0] => stdClass Object
(
[name] => Introduction
[id] => 798162f0-d779-46b6-96cb-ede246bf4f3f
[tags] => Array
(
[0] => client corp
[1] => version 2
)
)
[1] => stdClass Object
(
[name] => Chapter one
[id] => 761e1909-34b3-4733-aab6-ebef26d3fcb9
[tags] => Array
(
[0] => pro feature
)
)
)
I tried using an anonymous function like so:
$selectedTree = array_filter($tree, function($array) use ($selectedTags){
return in_array($array->tags, $selectedTags, true);
});
$selectedTags:
Array
(
[0] => client corp
)
The above is returning empty when I'd expect item 1 to be returned. No error thrown. What am I missing?
In case of in_array($neddle, $haystack). the $neddle must need to be a String, but you're giving an array that is why its not behaving properly.
But if you like to pass array as value of $selectedTags then you might try something like below:
$selectedTree = array_filter($tree, function($array) use ($selectedTags){
return count(array_intersect($array->tags, $selectedTags)) > 0;
});
Ref: array_intersect
If I am reading the question correctly, you need to look at each object in $tree array and see if the tags property contains any of the the elements in $selectedTags
Here is a procedural way to do it.
$filtered = array();
foreach ($tree as $key => $obj) {
$commonElements = array_intersect($selectedTags, $obj->tags);
if (count($commonElements) > 0) {
$filtered[$key] = $obj;
}
}
I was going to also post the functional way of doing this but, see thecodeparadox's answer for that implementation.

Retrieving correct record from multidimentional array

I'm having a mental freeze moment. If I have an array in the following format:
$myData = Array
(
[0] => stdClass Object
(
[id] => 1
[busID] => 5
[type] => SMS
[number] => 5128888888
)
[1] => stdClass Object
(
[id] => 2
[busID] => 5
[type] => APP
[number] => 5125555555
)
[2] => stdClass Object
(
[id] => 4
[busID] => 5
[type] => APP
[number] => 5129999988
[verified] => 1
[default] => 0
)
)
And I only have an var for ID of the record, how do I retrieve the rest of the detail for that set.
$myID = 2;
// get number 5125555555 and it's type
echo $myData[][$myID]['number']; // ???
The way you have your data arranged your going to have to loop through your array to identify the object corresponding to $myID.
foreach($myData as $object) if($object->id == $myID) echo $object->number;
The alternative is to arrange your $myData as an associative array with the id field as the key. Then you could access it simply with $myData[$myID]->number.
Actually it's an array that contains StdClass objects , try looping over $myData and access each attribute :
foreach ( $myData as $data )
{
print_r($data->id);
// ...
}
You can avoid loop by using following logic:
<?php
$myID = 2;
$myData = json_decode(json_encode($myData),1); // Convert Object to Array
$id_arr = array_column($myData, 'id'); // Create an array with All Ids
$idx = array_search($myID, $id_arr);
if($idx !== false)
{
echo $myData[$idx]['type'] . ' -- ' . $myData[$idx]['number'];
}
?>
Working Demo
Note: array_column is supported from PHP 5.5.
For lower versions you can use this beautiful library https://github.com/ramsey/array_column/blob/master/src/array_column.php
You can create a custom function to achieve this, you need to pass the array and id whose details you want and the function will return the array with matching id, like below
function detailsById($myData,$id){
foreach($myData as $data){
if($data->id == $id){
return $data;
}
}
}
Just call this function with your array and id..
$data=detailsById($myData,2);
echo "<pre>";print_r($data);
This will give you :
stdClass Object
(
[id] => 2
[busID] => 5
[type] => APP
[number] => 5125555555
)
And further to print 'number' and 'type' use $data array
$data['type'];
$data['number'];

Foreach loop array and stdclass object, getting values

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.

Categories