Let's say the JSON looks like this:
"response":{
"success":1,
"inventory":{
"apples" { "count": 1 },
"bananas" { "count": 53 },
etc
Then I have a PHP file that reads it like this:
<?php
$json = json_decode(file_get_contents(JSON URL));
foreach($json->response->inventory as $item)
{
echo $item->count; // would count 1 then 53
}
?>
How do I read the current "directory" (I have no idea what it is called) that I am in? As in how do I echo out "apples", "bananas" etc, depending on which one I'm foreach'ing.
I tried just printing out $item, but doesn't show anything.
Thanks in advance.
PHP's foreach syntax covers this with the => operator:
foreach ($json->response->inventory as $fruit => $item)
Related
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));
I have got this array from the Android developer whom I am working with and I have to get the values of the key name from the following array:
[
{
"data":"[{\"name\":\"step 1 kdfhghdkgjdf\\nkjdhfgkjhdkjghd\\nkdfjhgkjdhfg\\n\\n\\ndfjhgkjdfjhgdfgd\\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\\ndkjhjdf\\njhkdfhkghdkfhgkdhg\\n\\n\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\\n\\n\\ndfhjk\"}]",
"status":1
}
]
I have tried doing the following:
<?php
$s = '[
{
"data": "[{\"name\":\"step 1 kdfhghdkgjdf\\nkjdhfgkjhdkjghd\\nkdfjhgkjdhfg\\n\\n\\ndfjhgkjdfjhgdfgd\\n\"},{\"name\":\"step 2 dhfgkjdfhkhkjchjkfd\\ndkjhjdf\\njhkdfhkghdkfhgkdhg\\n\\n\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\"},{\"name\":\"step 3 kkkkkkkkkk\"},{\"name\":\"step 4 ljlejrhlflhgf\\n\\n\\ndfhjk\"}]",
"status": 1
}
]';
$obj = json_decode($s,true);
echo $obj[0]['data']
?>
Which gives me following output:
[
{
"name": "step 1 kdfhghdkgjdf kjdhfgkjhdkjghd kdfjhgkjdhfg dfjhgkjdfjhgdfgd "
},
{
"name": "step 2 dhfgkjdfhkhkjchjkfd dkjhjdf jhkdfhkghdkfhgkdhg dfjhgkjdfhgdfhgkjdhfgkjhdf"
},
{
"name": "step 3 kkkkkkkkkk"
},
{
"name": "step 4 ljlejrhlflhgf dfhjk"
}
]
But I want just the values of the key name like:
step 1 kdfhghdkgjdf kjdhfgkjhdkjghd kdfjhgkjdhfg dfjhgkjdfjhgdfgd
step 2 dhfgkjdfhkhkjchjkfd dkjhjdf jhkdfhkghdkfhgkdhg dfjhgkjdfhgdfhgkjdhfgkjhdf
step 3 kkkkkkkkkk
.
.
.
My question is similar to this one:
Get value from JSON array in PHP
except the format is different.
Can I get the values in this format? If so, how? If not, is the format incorrect?
Assuming $obj[0]['data'] actually has the JSON that you posted, just decode and extract the name columns:
foreach(array_column(json_decode($obj[0]['data'], true), 'name') as $name) {
echo $name;
}
First of all you have not a json-structure inside the "data" field, but just a string, which contains json data.
Therefore you did it wrong, when convert the data into a constant value. You have to double all backslashes first.
Then you can get the "data" element and perform json_decode once more.
<?php
$s = '[
{
"data": "[{\\"name\\":\\"step 1 kdfhghdkgjdf\\\\nkjdhfgkjhdkjghd\\\\nkdfjhgkjdhfg\\\\n\\\\n\\\\ndfjhgkjdfjhgdfgd\\\\n\\"},{\\"name\\":\\"step 2 dhfgkjdfhkhkjchjkfd\\\\ndkjhjdf\\\\njhkdfhkghdkfhgkdhg\\\\n\\\\n\\\\ndfjhgkjdfhgdfhgkjdhfgkjhdf\\"},{\\"name\\":\\"step 3 kkkkkkkkkk\\"},{\\"name\\":\\"step 4 ljlejrhlflhgf\\\\n\\\\n\\\\ndfhjk\\"}]",
"status": 1
}
]';
$obj = json_decode($s,true);
$data = json_decode($obj[0]['data'], true);
foreach($data as $item) {
print($item['name'] . "\r\n");
}
I have a json like this:
"achievementsProgress": [
{
"value": 11,
"globalID": 23000000
},
{
"value": 11,
"globalID": 23000001
},
{
"value": 11,
"globalID": 23000002
},
{
"value": 147,
"globalID": 23000003
},
{
"value": 147,
"globalID": 23000004
},
{
"value": 147,
"globalID": 23000005
},
.....
]
It goes on like that and I need to be able to read the "value" field of every 3rd.
So globalID 23000002, 23000005, 23000008, 230000011 etc. All the way up to and including 65. And then I need to save those as variable names like:
$achievement1 for globalID 23000002
$achievement2 for globalID 23000005
etc.
Now I assume this has to be done in a loop.
So far I have this much.
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true)
and it would be
$data['achievementsProgress'] to get to the list of the above json.
How would I go about doing this?
Here is one way to do it. I think any way you'll be able to do this will need to involve variable variables.
$x = 1; // start a counter for your variable names
for ($i=2; $i < 65; $i+=3) { // start at index 2 (3rd value) and increment by 3
if (isset($data['achievementsProgress'][$i])) { // just in case there aren't actually 65
// Use variable variables to create the $achievement variables you want
${"achievement$x"} = $data['achievementsProgress'][$i]['value'];
}
$x++;
}
This example uses complex string syntax to create the variable variable.
Better do it like this:
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true);
$items=$data->achievementsProgress;
$result=[];
$i=1;
foreach($items as $item)
if($i++%3==0)
$result[$item->globalID]=$item->value;
//now $result contains map of data you wanted globalid => value
Now you can access it like this:
$result['23000000'] == 11 and so on
I have a JSON file that, in essence, is structured like this:
[{
"name": "James",
"reviews": [
{
"stars": 5,
"body": "great!"
},
{
"stars": 1,
"body": "bad!"
}
]
},
{
"name": "David",
"reviews": [
{
"stars": 4,
"body": "pretty good!"
},
{
"stars": 2,
"body": "just ok..."
}
]
}]
Now when positing new review data for David to a PHP script, how do I target David's specific "reviews" and append it?
I have already decoded everything correctly and have access to both the decoded file and post information. I just don't know how to target David's specific reviews in the JSON array... Thank you in advance!
UPDATE - Just to be clear, everything is decoded already, the POST data and the JSON file from the server. I just need to know how to target David's reviews specifically and append it.
UPDATE 2 - Everyone, please also understand that this is in the case that the index is not known. Doing [1] would be awesome, but when someone submits, they won't know what index it is. The loop for the rendering is being done in AngularJS btw, so can't assign anything on the PHP side for the front-end.
You will have to make use of a for-loop/foreach to iterate through the array testing where arr['name'] === 'David',
then you can access arr['reviews'].
foreach ($array as $person)
{
if ($person['name'] === 'David')
{
$person['reviews'][] = array("stars"=> 3,"body"=> "pretty cool!");
break;
}
}
Edit:
You could also make a generic function for this
function findElem(arr,field,e)
{
foreach ($arr as $elem)
{
if ($elem[field] === e)
{
return $elem;
}
}
return null;
}
to call:
$elem = findElem(myArray,'name','David');
if ($elem !== null)
$elem[] = array("stars"=> 3,"body"=> "pretty cool!");
Looks like more work, but if you are going to do it repeatedly then this helps.
PHP >= 5.5.0 needed for array_column or see below for an alternate:
$array[array_search('David', array_column($array, 'name'))]['reviews'][] = array(
'stars'=>1,'body'=>'meh'
);
Instead of array_column you can use:
array_map(function($v) { return $v['name']; }, $array);
If you want specifically david's reviews, and only david's reviews... assuming that $array holds the json_decoded array:
$david_reviews = $array[1]["reviews"];
foreach($david_reviews as $review){
//Do code to retrieve indexes of array
$stars = $review["stars"] //5
$body = $review["body"] //Great!
}
If you're looking to grab reviews for each result, then user2225171's answer is what you're looking for.
json_decode($json, true) will return you the simple array of data. Then save what you need and save back with json_encode()
I have searched SO but couldn't find an answer.My PHP script is receiving some JSON by http post that looks like this:
{
"task": [
{
"task_id": "3",
"task_due": "Oct 26 11:25",
"task_completed": "FALSE",
"task_desc": "fff",
"task_time": "20131026_112531",
"task_name": "fff"
},
{
"task_id": "2",
"task_due": "Oct 26 11:25",
"task_completed": "FALSE",
"task_desc": "rff",
"task_time": "20131026_112522",
"task_name": "xff"
},
{
"task_id": "1",
"task_due": "Oct 26 11:25",
"task_completed": "FALSE",
"task_desc": "fggg",
"task_time": "20131026_112516",
"task_name": "ff"
}
]}
As you can see, there are 3 items, but when I turn it into a PHP array object and count the items, I'm returned 1, when it should be 3, here is my PHP code:
$json_tasks = $_POST["json_array"];
$task_array = json_decode($json_tasks,true);
echo count($task_array);
And echo count prints out '1' not '3'.
Try echo count($task_array['task']);
In general, if you wonder what the structure of the value of a variable $var is, do a
<pre><?php var_export($var, true); ?></pre>
Advantage of this function over alternatives such as serialize and print_r is, that it prints PHP code (and is thus readable by anyone who understands PHP (which is likely if you program in PHP)). Disadvantage of var_export is, that it cannot handle circular structures (e.g. if $a->b == $a), but neither can JSON.
Well the 3 items are in 1 item "task" so, you have one array named task and the 3 elements are in it
try
echo count($task_array['task']);
EDIT :
please use the below code to print the array in correct pattern
echo '<pre>';
print_r($task_array['task']);
exit();
$task_array = json_decode($json_tasks);
count($task_array->task);
EX: 3
From Taiwan
try this code, here i can able to count the number of objects with specific value
here's my data.json file content
{"likes":[
{"user_id":1,"time":"12:04pm"},
{"user_id":2,"time":"02:04pm"},
{"user_id":67,"time":"11:04pm"},
{"user_id":1,"time":"12:04pm"}
]}
here's the php code
<?php
$jsonData = file_get_contents("data.json");
$data = json_decode($jsonData,true);
$total = 0;
foreach ($data["likes"] as $value) {
if($value["user_id"]==1){
$total = $total+1;
}
}
echo $total;
?>
output will be
2