Nested Json php for loop status[0] issue - php

Hi I have a Json format like below:
{
"result":0,
"status":[
{
"id":"00001",
"vid":"yes"
},
{
"id":"00002",
"vid":"yes"
},
{
"id":"00003",
"vid":"no"
}
]
}
I want to use the json_decode function in PHP to decode the id values such as below:
00001
00002
00003
here is the code I am using:
$url = file_get_contents("URL");
foreach(json_decode($url, true) as $key=>$value){
foreach($value->status[0] as $key1=>$value1){
echo $value1->id;
}
}
The problem seems to be with status[0] as far as I know using status[0] is the only way to select the status key. However I can't get the loop to work correctly.
I get the error: Trying to get property of non-object meaning status[0] is not finding status in the Json array however I have no idea why this is since it works when I pull a value like:
$id = $url->status[0]->id;
If anyone has any suggestions or advice I'd greatly appreciate it. Thanks

I removed some commas from your json data.
Code: demo: https://3v4l.org/C1Mda
$json = '{"result":0,"status":[{"id":"00001"},{"id":"00002"},{"id":"00003"}]}';
foreach(json_decode($json, true)['status'] as $status){
echo $status['id'] , "\n";
}
Output:
00001
00002
00003
Because you are using json_decode's true parameter, an array is generated. You need to use square bracket syntax.
Or you can use objects:
foreach(json_decode($json)->status as $status){
echo $status->id , "\n";
}

Your JSON is invalid look { "id":"00001", }
And json_decode( $json, false ) should be.
working solution:
$json = '{
"result":0,
"status":[{"id":"00001"},
{"id":"00002"},
{"id":"00003"}
]
}';
$data = json_decode($json, false);
foreach ($data->status as $status){
echo $status->id;
}

You can just use array_column to extract the id values from the status element of your JSON (once it is corrected by removing the superfluous commas):
$ids = array_column(json_decode($json, true)['status'], 'id');
print_r($ids);
Output:
Array (
[0] => 00001
[1] => 00002
[2] => 00003
)
Demo on 3v4l.org

Related

How to locate an array in a php object with no key

I have a database of zip codes from The Zip Code Database Project that came as a .csv file. I converted it to json and it has no key for each array, they look like this:
[
{
"zipcode": 35004,
"state abbreviation": "AL",
"latitude": 33.606379,
"longitude": -86.50249,
"city": "Moody",
"state": "Alabama"
}
]
I have figured out how to search all of the arrays and locate a matching zip code but I can't figure out how to make that search return data about the array that it found it in.
I can search like this:
$filename = './assets/data/zips.json';
$data = file_get_contents($filename);
$zipCodes = json_decode($data);
$inputZip = 55555;
foreach ($zipCodes as $location) {
if ($inputZip == $location->zipcode) {
echo "Success";
}
}
Can anyone tell me how I can use this search (or a better idea) to store the latitude and longitude associated with the searched zip code to two variables? I have wasted nearly my whole weekend on this so any and all help is greatly appreciated.
Also, I have no issue using the raw csv file to perform this function, I just couldn't get as far as I did with json.
Thanks everyone!
To find out the index of an array by a property of the array items, use array_column to get just the values of that column/property, then use array_search to find the index.
<?php
$inputZip = 35004;
$index = array_search($inputZip, array_column($zipCodes, 'zipcode')); // 0
print_r($zipCodes[$index]); // the entire object
https://3v4l.org/TAXQq
Based on your code:
foreach ($zipCodes as $index => $location) { // index is a key
if ($inputZip == $location->zipcode) {
echo "Index is ".$index;
break;
}
}
var_dump($zipCodes[$index]);
I should note that it seems you are doing something wrong because you don`t suppose to store your data like this and loop through array all the time.
To get the keys of an array that is filtered due to certain parameters that must be met you could use array_keys and array_filter.
For Example
$array = [1,2,1,1,1,2,2,1,2,1];
$out = array_filter($array,function($v) {
return $v == 2;
});
print_r(array_keys($out));
Output
Array
(
[0] => 1
[1] => 5
[2] => 6
[3] => 8
)
Try the above example in PHP Sandbox
To match your actual data structure.
$json = '[{"zipcode": 35004,"state abbreviation": "AL","latitude": 33.606379,"longitude": -86.50249,"city": "Moody","state": "Alabama"},{"zipcode": 35004,"state abbreviation": "AL","latitude": 33.606379,"longitude": -86.50249,"city": "Moody","state": "Alabama"},{"zipcode": 35005,"state abbreviation": "AL","latitude": 33.606579,"longitude": -86.50649,"city": "Moody","state": "Alabama"}]';
$array = json_decode($json);
$out = array_filter($array, function($v) use ($inputZip) {
return $v->zipcode == $inputZip; // for the below output $inputZip=35004
});
print_r(array_keys($out));
Output
Array
(
[0] => 0
[1] => 1
)
Try the example in PHP Sandbox

Extracting one object/group out of a JSON array and save it to a new file using PHP. I am hung up on the array part of the code

I have the following json structure I am trying to loop through and extract products from:
[]JSON
->{0}
-->[]username
-->[]avatar
-->[]rep
-->[]products
-->[]groups
-->[]feedbacks
-->[]online
-->[]staff
I am trying to ave only the products object into as a JSON file. This is the only result I need and delete/unset the rest:
[]JSON
->{0}
-->[]products
But I seem to be a bit confused, as I am not to familiar with how arrays work around PHP. Here is an angle I am currently trying:
<?php
$str = file_get_contents('test.json');
$json_decoded = json_decode($str,true);
foreach($json_decoded as $index){
unset($json_decoded[$index][???]);
}
file_put_contents('cleaned.json', json_encode($json_decoded));
?>
I added ??? where I am lost, this is about as far as I have gotten. I keep getting super confused. I know the structure will always be the same as above so I can technically just remove username,avatar,rep,groups,feedbacks,online, and staff seperatly. Which is just fine.
Here is an example of the json structure:
[{"username":["1"],"avatar":["yellow"],"rep":["etc"],"products":["Big"],"groups":["small"],"feedbacks":["small"],"online":["small"],"staff":["small"]}]
Thank you in advance, even a push in the right direction is much appreciated.
You could compose a new products array like this :
$products = [];
foreach($json_data as $value) {
$products[]['products'] = $value['products'];
}
file_put_contents('cleaned.json', json_encode($products));
This will results json objects like this :
[
{
"products": ["Big-01"]
},
{
"products": ["Big-02"]
},
{
"products": ["Big-03"]
},
{
"products": ["Big-04"]
},
{
"products": ["Big-05"]
}
]
From your snippet. try this.
<?php
$str = '[{"username":["1"],"avatar":["yellow"],"rep":["etc"],"products":["Big"],"groups":["small"],"feedbacks":["small"],"online":["small"],"staff":["small"]}]';
$json_decoded = json_decode($str,true);
foreach($json_decoded as $value) {
$products = $value['products'];
}
print_r( $products);
?>
output
Array
(
[0] => Big
)
Create a new array ($products), iterate over the old array, and set products as the one property instead of unseting every single array.
$products = [];
foreach ($json_decoded as $index) {
$products[$index] = [
'products' => $json_decoded[$index]['products']
];
}
file_put_contents('cleaned.json', json_encode($products));

Decode JSON from MySQL

I have JSON string in MySQL database like this
{
"string1": {
"substring1": 1234
},
"string2": {
"substring2": "substring2.1",
"substring3": "substring3.1",
"substring4": {
"substring4.1": 1234,
"substring4.2": 1234,
"substring4.3": 1234
}
}
}
I put those data from MySQL into $string, then I decode it with this function
$json_a = json_decode($string,true);
echo $json_a['string1']['substring1'];
But the result is nothing.
Then I tried to change the $string into
$string = '{"string1":{"substring1":1234},"string2":{"substring2":"substring2.1","substring3":"substring3.1","substring4":{"substring4.1":1234,"substring4.2":1234,"substring4.3":1234}}}';
Next, I use the same function as above and works fine.
Is there any specific things we should do before decode it from mysql?
Thank you
The outer layer of the data you have is not an array, in fact you don't have any arrays in the data at all. Don't use [0] in your PHP.
Access your index with
echo $json_a['string1']['substring1'];

Getting Value From Json Data Inside Array

I have a problem to get the value from json data inside array when the data is more than one.
When my data only one like this:
$mydata='[{"firstName":"Ana","height":5.3}]';
I can just access the height of Ana by substring-ing it first and the decode it, like this:
$mydata= substr($mydata, 1, -1);
$obj = json_decode($mydata);
print $obj->{'height'};
The problem is when the data look like this:
$mydata='[{"firstName":"Ana","height":5.3},{"firstName":"Taylor","height":5.11}]';
How can I get the height of Ana?
print $obj->{0}->{'height'}; //doesn't work.
Please help. Thankyou in advance.
use json_decode
$b_arr=json_decode($mydata,true);
$b_arr[0]['height'];//0 is index for array
You can convert with json_decode and iterate through your array to get your specific data:
<?php
$mydata='[{"firstName":"Ana","height":5.3},{"firstName":"George","height":7.3}]';
$json = json_decode($mydata, true);
foreach($json as $key => $value) {
if($value['firstName'] == 'Ana') {
echo $value['height'];
break;
}
}
?>

JSON decode with PHP: Key started with # sign

JSON is like
{
"#http_status_code": 200,
"#records_count": 200,
"warnings": [],
"query": { ... ...
In PHP
$data = json_decode($json_entry);
print $data->#http_status_code; //returns error
print $data->http_status_code; //returns nothing
How can I retrieve status code?
1) As Object way
$data = json_decode($json_entry);
print $data->{'#http_status_code'};
2) OR use as array way by passing second argument as true in json_decode
$data = json_decode($json_entry, true);
print $data['#http_status_code'];
Try json_decode to get the json in form of array ..
$json_array = json_decode($data, true);
$required_data = $data['required_key']
with reference to your particular problem .. you will get array as
Array
(
[#http_status_code] => 200
[#records_count] => 200
[warnings] => Array
(
)
....
)
so you can access you data as $data['#http_status_code']
To access an object property that has funky characters in the name, quote the name and stick it in braces.
print $data->{'#http_status_code'};
Or, say $data = json_decode($json_entry, true); to get the data back as an array.
PHP cwill give syntax error when you do this:
$data->#http_status_code;
it looks for $http_status_code variable which is not present
so in order to make this work you have to do this:
echo $data->{'#http_status_code'};
Try this:
$data = json_decode($json_entry, true);
print $data["#http_status_code"];

Categories