PHP Specific JSON Array nesting level Confusion - php

I was wondering if someone could help please. I have a JSON feed from an API, and I can never figure out the levels to get the information I need?
the JSON is below
{
"sourceId": "1234",
"sourceType": "MONITOR",
"searchMeta": {
"startTimestamp": 1462361513,
"endTimestamp": 1462508560,
"maxResults": 10000,
"metricType": [
"clients"
],
"family": [
"Product"
],
"metricsInterval": "M5"
},
"clients": {
"One": [
{
"timestamp": 1462361400,
"avg": 2,
"min": 1,
"max": 3,
"probes": 6,
"samples": 3,
"sources": [
"123",
"234",
"345",
"456",
"567",
"789"
]
},
I was wanting to get the Probes value and the Samples value into a variable
foreach($json['clients'] as $range => $product){
echo $product['timestamp']." Probes: ".$product['probes']." Samples: ".$product['samples']." <br>";
}
Thanks in advance

I assume you'll have a range of clients (hence the loop). So you'll need to loop each client too as it's an array of object's.
If you visualise it, that looks like this:
CLIENTS = ARRAY(
1 => ARRAY( OBJECT{} ), // you want the OBJECT{}
....etc
)
So the below loop will get it for you.
$data = json_decode($json, TRUE);
foreach($data['clients'] as $range => $product) {
foreach($product as $element){
echo $element['timestamp']." Probes: ".$element['probes']." Samples: ".$element['samples']." <br>";
}
}
Example/Demo
Returns the following:
1462361400 Probes: 6 Samples: 3 <br>

Try this.
$data = json_decode($json,true);
foreach($data['clients'] as $client){
echo $client['timestamp']." Probes: ".$client['probes']." Samples: ".$client['samples']." <br>";
}

The demand of OP:
I was wanting to get the Probes value and the Samples value into a
variable
Simple just name your json file as $json.
$arr = json_decode($json);
echo $samples = $arr->clients->One[0]->samples; //3
echo $probes = $arr->clients->One[0]->probes; //6

Related

Accessing Data in Array - Non-Object Error PHP

I'm populating an array like this:
$POarray = array();
foreach($orders as $order)
{
$total = OrderItems::where('OrderID', $order->OrderID)->sum('TotalPrice') * (1 + $LRmarkup);
$arraydata = array(
'Name' => $order->OrderNumber,
'Total' => $total);
$POarray[] = $arraydata;
}
This results in the contents of the $POarray variable being:
[
{
"Name": "DS-BS-18102654",
"Total": 241.4655
},
{
"Name": "test test",
"Total": "600.00"
}
]
I am attempting to access this data like this:
$purchase1name = $POarray[0]->Name;
$purchase1total = $POarray[0]->Total;
And I am getting this error:
"Trying to get property of non-object"
Shouldn't this work?
Thank you for taking the time to respond.
$POarray is not an object.
Try:
$purchase1name = $POarray[0]['Name'];
$purchase1total = $POarray[0]['Total'];
You need to do this way after decoding it using json_decode(),
<?php
$key='[
{
"Name": "DS-BS-18102654",
"Total": 241.4655
},
{
"Name": "test test",
"Total": "600.00"
}
]';
$POarray = json_decode($key);
echo $POarray[0]->Name;
echo $POarray[0]->Total;
?>
DEMO: https://3v4l.org/JvCam
You can also use this.
array_get($POarray[0], 'Name');
array_get($POarray[0], 'Total');
For more information: https://laravel.com/docs/5.7/helpers

Printing nested associative array in PHP

I'm using this code $json_output = (json_decode($json, true)); to transform from JSON to an associative array in PHP.
The resulting array looks too compĺex to me, I need to print only some keys and values but they are nested and so far I haven't been able to do it, the examples I had follow for printing are too basic for this.
This is part of my JSON:
{
"project": {
"company": "Company Name SA de CV",
"name": "Project Name",
"files": [
{
"project-id": "666666",
"filenameOnDisk": "HH-ORG-CMD-GUI-File.docx",
"uploaded-date": "2018-01-29T21:20:56Z",
"private": "0",
"version-id": "3939061",
"status": "active",
"tags": [
{
"name": "OPD",
"id": "25047",
"color": "#9e6957"
}
],
"id": "3796128",
"last-changed-on": "2018-01-29T21:21:46Z",
"versions": [],
"uploaded-by-user-first-name": "Someone",
"uploaded-by-user-last-name": "Anything",
"name": "HH-ORG-CMD-GUI-GUIA_RAPIDA_PARA_CREAR_PROCESOS",
"size": "262747",
"category-name": "Instructivos"
},
{
"project-id": "666",
etc...,
},
When parsed looks like
How do I print (lets say) filenameOnDisk and id keys of the Files array.
I don't know how to get to that nested array.
echo $json_output['project']['files'][0]['project-id'];
echo $json_output['project']['files'][0]['filenameOnDisk'];
echo $json_output['project']['files'][0]['version-id'];
Or you could put it in a foreach loop using an array of values you want (as long as they're all in the 'files' array). Eg.
$wantedValues = array("project-id","filenameOnDisk","version-id");
foreach ($wantedValues as $value) {
echo $json_output['project']['files'][0][$value];
}
I Just needed to add a couple of lines at the code provided by #SeeSamRun in order to get the full "Files" array.
$filesArray = $json_output['project']['files'];
$filesSize = count($filesArray);
$wantedValues = array("project-id","filenameOnDisk","version-id");
for ($i=0; $i < $filesSize; $i++) {
foreach ($wantedValues as $value) {
echo $json_output['project']['files'][$i][$value];
}
}

access to properties of an array contain json formatted elements in laravel

suppose I have an Array like this :
$myArray =
[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]
Each element of array has json format. and now I want to get name of element that have id of 87 for example.
Firstly How can I found that is there element with this id then get name property of that?
Decode JSON string into array. Then use Laravel's array_first method.
<?php
$myArray = '[{"id": 86,"name": "admin/login"},{"id": 87,"name": "admin/logout"},{"id": 88,"name": "admin/desktop"}]';
// Decode into array
$array = json_decode($myArray, true);
// Find item with correct id
$result = array_first($array, function($key, $value){
return $value['id'] === 87;
}, false);
if ($result) {
echo 'Item found, it\'s name is: '.$result['name'];
}
If you have id you like to find in variable, you have to use use construct.
// ID to search for
$searchID = 87;
// Find item with correct id
$result = array_first($array, function($key, $value) use($searchID){
return $value['id'] === $searchID;
}, false);
Try using this:
$newArray = json_decode($myArray);
and you'll get type of array
[
[
"id"=> 86,
"name"=> "admin/login"
],.....
........
]
Your $myArray is incorrect so, assuming it is a json string you can do this in the following way :
At first json_decode it into an arry.
Loop through the elements to find out you desired value(87).
Keep a flag which will tell if you have actually found any value.
<?php
$myArray =
'[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]';
$myArray = json_decode($myArray , true);
$found = 0;
foreach($myArray as $anArray)
{
if($anArray['id'] == 87)
{
var_dump($anArray['name']);
$found = 1;
}
}
if($found == 1)
{
var_dump("Element found.");
}
else
{
var_dump("Element not found. ");
}
?>

Extract each level data with php

The following is the JSon data.
{
"statusType": "OK",
"entity": [
{
"category": "category1","difficultyLevel": "Easy",
"quizAnswerChoices": [{"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}, {"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}]
}
],
"entityType": "java.util.ArrayList",
"status": 200,
"metadata": {}
}
I need to parse
- entity
- quizAnswerChoices (count the item)
How to retrieve each choiceText etc
Use
$json='{
"statusType": "OK",
"entity": [
{
"category": "category1","difficultyLevel": "Easy",
"quizAnswerChoices": [{"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}, {"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}]
}
],
"entityType": "java.util.ArrayList",
"status": 200,
"metadata": {}
}';
$encodedJson= json_decode($json,true);
$quizAnswerChoices=$encodedJson['entity'][0]['quizAnswerChoices'];
echo 'Count: '.count($quizAnswerChoices);
Use this
$arry = json_decode($json,true);
foreach ($arry['entity'] as $ke => $ve) {
foreach ($ve['quizAnswerChoices'] as $k => $v) {
print_r($v);
}
}
Lets consider you are recieving this json in a variable called "$contents".
All you have to do is decode it:
$decoded = json_decode($contents, true); //True so, the decoded object will be converted into an ssociative array
print_r($decoded);
If you do a json_decode like
$data = json_decode(json_data);
Then $data will be a traversable array
$data['entity']['quizAnswerChoices'] etc
Use json_decode to convert json to array
$dataArray = json_decode($json_string, true)
$dataArray['entity']; // entity
$dataArray['entity']['quizAnswerChoices']; // quizAnswerChoices
$dataArray['entity']['quizAnswerChoices']; // quizAnswerChoices
count($dataArray['entity']['quizAnswerChoices']); // quizAnswerChoices count

PHP Create Multidimension Array for JSON output

I feel terrible even asking because I have been TRYING to understand and comprehend other peoples examples this is what i'm TRYING to accomplish
{
"field": [
{
"appid": 0,
"page": 0,
"fieldname": "Sweet",
"value": "Tammy Howell"
},
{
"appid": 1,
"page": 1,
"fieldname": "Cecilia",
"value": "Shana Jordan"
},
{
"appid": 2,
"page": 2,
"fieldname": "Merritt",
"value": "Copeland Pena"
}
]
}
I need to be able to make the above JSON output happen when doing an SQL SELECT statement
Here is my currentCode
$x = 0;
$userFieldsResult = mysqli_query($database_id, "SELECT * FROM theDB.DynamicFields ORDER BY Page, Priority") or die (mysqli_error($database_id));
if (mysqli_num_rows($userFieldsResult)<=0)
{
echo "nothing found";
exit;
} else
{
while($row = mysqli_fetch_array($userFieldsResult))
{
$userFields[$x]['appid'] = $row['appid'];
$userFields[$x]['page'] = $row['page'];
$userFields[$x]['fieldname'] = $row['fieldname'];
$userFields[$x]['value'] = $row['value'];
$x++;
}
echo json_encode($userFields);
exit;
}
echo json_encode($userFields);
This is normally how i just been outputting json so they each are just part of 1 array looping, but I am trying to understand how to create more "in-depth" JSON arrays so they have a specific identifier before they list out the information.
[
{
"appid": 0,
"page": 0,
"fieldname": "Sweet",
"value": "Tammy Howell"
},
{
"appid": 1,
"page": 1,
"fieldname": "Cecilia",
"value": "Shana Jordan"
},
{
"appid": 2,
"page": 2,
"fieldname": "Merritt",
"value": "Copeland Pena"
}
]
In my example I just want to be able to have "field" be the "upper" part of the array that holds all the information as i showed in the example above.
You need to add field as parent array to your array.
Change from
echo json_encode($userFields);
Into
$json = array('fields' => $userFields);
echo json_encode($json);
In this particular configuration, you are being returned an object with properties, of which, the property's value may be an array.
So what you should actually be doing is creating a stdClass object in PHP and assigning it a property of "field" which is an empty array. Then you can push into this array stack.
$obj = new stdClass();
$obj->fields = array();
while(....){
$obj->fields[$x]['appid'] =
$obj->fields[$x]['appid'] = $row['appid'];
$obj->fields[$x]['page'] = $row['page'];
$obj->fields[$x]['fieldname'] = $row['fieldname'];
$obj->fields[$x]['value'] = $row['value'];
}
Now you can json encode the object and return it.
echo json_encode($obj);

Categories