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
Related
everyone, I was just trying to find out a way to get the value of a link from a JSON array , after I have searched the array with help of Id. I am using PHP's file_get_contents and the webpage from which information is to be taken looks like
[{
"id":"2972",
"name": "AbC",
"link":"any link",
"epg": "any link",
"dur": "disabled",
"language": "y",
"category": "TOP 100",
"logo": "any url here"
},
{
"id": "1858",
"name": "Efg",
"link": "url",
"epg": "url",
"dvr": "disabled",
"language": "E",
"category": "TOP 100",
"logo": "url"
}]
From here suppose I have been given an Id 1858 so I have to find a link from the array of Id having 1858
I am a beginner in PHP and was just fidgeting around with a piece of code and tried to get its solution and a big Thanks To You For Your Answer and valuable Time.
if you are using file_get_contents('php://input'); then you should try this to access json data
$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json); //parse json data in php array
// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
$url = $obj->link;
echo $url; // do something with link
//you can use break; statement if you found your element and terminate the loop
}
}
You can use array_column, to map pairs of json keys/values:
<?php
$json ='
[
{
"id": 3,
"link": "http:\/\/example.com\/3"
},
{
"id": 5,
"link": "http:\/\/example.com\/5"
}
]';
$data = json_decode($json, true);
if($data !== null) {
echo array_column($data, 'link', 'id')[5] ?? null;
}
Output:
http://example.com/5
To understand this we can see the result of array_column.
var_export(array_column($data, 'link', 'id'));
Output:
array (
3 => 'http://example.com/3',
5 => 'http://example.com/5',
)
So with the above code, we are checking for and outputting the associated index of 5 (the original id).
I'm trying to return json response in the correct format but I am getting an extra 'comma' in the returned code (comma after the last item 'Pencil'):
{
"results": [{
"ItemID": 1,
"ItemName": "Ball"
}, {
"ItemID": 2,
"ItemName": "Pen"
}, {
"ItemID": 3,
"ItemName": "Pencil"
},
}]
}
I tried different things but I can't get rid of it. Would anybody have any idea how to remove it?
The code that i have is this:
<?php
print '{"results":[';
for ($i=0; $i <$numrows; $i++) {
$stmt->fetch();
$JSONArray = array(
"ItemID" => $ItemID,
"ItemName" => $ItemName
);
print ",";
print json_encode($JSONArray);
}
print "]}"
?>
You're doing it ENTIRELY wrong. You're outputting multiple independent JSON strings, which is outright wrong. JSON is a monolithic "structure", and building it piece-wise is highly risky.
Simple: DOn't do that.
You build a standard PHP array, then do ONE SINGLE encoding when you're completely done building:
$arr = array();
for(...) {
$arr[] = ... add stuff ..
}
echo json_encode($arr);
First, fetching into bound variables is causing you an extra step, second, you don't need to construct any JSON. Just get all of your rows into the proper array structure and encode:
$result = $stmt->get_result();
while($rows['results'][] = $result->fetch_array(MYSQLI_ASSOC)){}
echo json_encode($rows);
If your system supports it, just use this instead of the while loop:
$rows['results'] = $result->fetch_all(MYSQLI_ASSOC);
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
I have run into a problem that is a little irritating. Here is my PHP code. Ignore where the variables are coming from. This is for shopping-cart functionality but it is applicable in many different areas.
$data_set = json_decode(stripslashes($_POST['varA']), true);
$pid = $pid['product_id'];
$quantity = $pid['quantity'];
$_SESSION['cartid'] = $_SESSION['cartid'] + 1;
$product_data = array("Product_ID" = > $pid, "quantity" = > $quantity, "cartid" = > $_SESSION['cartid']);
My issue is occurring at this place in the code. I first check to see if the Session variable has a value in it, if not then it proceeds to create an associative array.
if (empty($_SESSION['cart_items'])) {
$_SESSION['cart_items'] = array("items" = > $product_data);
} else {
array_push($_SESSION['cart_items']['items'], $product_data);
}
echo json_encode($_SESSION['cart_items']);
The end result after the first item is "added" looks like this:
{
"items": {
"Product_ID": "2",
"quantity": "1",
"cartid": 1
}
}
However, after several the first add, every value gets a key:
{
"items": {
"0": {
"Product_ID": "2",
"quantity": "1",
"cartid": 2
},
"1": {
"Product_ID": "2",
"quantity": "1",
"cartid": 3
},
"Product_ID": "2",
"quantity": "1",
"cartid": 1
}
}
How do I prevent these keys from occuring? Is this possible? If not, how can this be re-written so that the keys are added every time? And is this possible to parse and loop through in JS on the front end?
Sorry I have so many questions. Any help is really appreciated.
In the first iteration, the $_SESSION['cart_items'] is empty, so you run this:
$_SESSION['cart_items'] = array("items" => $product_data);
This creates $_SESSION['cart_items']['items'] but you populate it with just the product by itself; you should define it as an array instead:
$_SESSION['cart_items'] = array("items" => array($product_data));
This creates an array with a single item which you can later extend with array_push.
Having said that, you can replace the whole condition with just:
$_SESSION['cart_items']['items'][] = $product_date;
PHP will automatically create an empty array if it didn't exist yet, followed by adding the product data as the next element.
This is because of this line:
$_SESSION['cart_items'] = array("items" = > $product_data);
You essentially say in that line that 'items' key has product data, instead of key in items. It should be:
$_SESSION['cart_items']['items'] = array($product_data);
Keys -will- always occur, unless you want data to overwrite another. If you do not want keys (0,1 etc) then the only other option is merging data. In which case it would be:
$_SESSION['cart_items']['items']+=$product_data;
..but I don't think that is what you want.
You don't need the items, try the below way.
if (empty($_SESSION['cart_items'])) {
$_SESSION['cart_items'] = array($product_data);
} else {
$_SESSION['cart_items'][] = $product_data;
}