How do I get all the keys in JSON within PHP? - php

How do I get all of the keys and loop through them, echoing each one, from a JSON object array?
Here is my code:
/* SAMPLE JSON THAT IS SENT
$mystring = '{
"display_name": "Silverware",
"fields": [
{
"field_name": "Age",
"sort_order": 1,
"required": 0,
"view_type": "text",
"description": "",
"multi_value": 0,
"char_count": 255
},
{
"field_name": "Brand",
"sort_order": 2,
"required": 0,
"view_type": "multiselect",
"description": "",
"multi_value": 1,
"char_count": 255
}
]
}';
*/
$json = json_decode($HTTP_RAW_POST_DATA);
$arr = $json->{'fields'};
// This is how I print a specific value
//print $arr[0]->{'field_name'};
Adding the following isn't working for me:
foreach ($arr as $k => $v) {
echo $k', ';
}

Use true for the second parameter of json_decode().
foreach ($j['fields'] as $field) {
$keys = array_keys($field);
foreach ($keys as $key) {
echo $key;
}
}

Related

Parse Json key/values of a key's value using JObject using PHP

Please can any help me on this, to remove all keys that have values of N/A, -, or empty strings. If one of the values appear in an array then remove that single item from the array
{
"name": {
"first": "Robert",
"middle": "",
"last": "Smith"
},
"age": 25,
"DOB": "-",
"hobbies": [
"running",
"coding",
"-"
],
"education": {
"highschool": "N/A",
"college": "Yale"
}
}
Expecting result would be:
{
"name": {
"first": "Robert",
"last": "Smith"
},
"age": 25,
"hobbies": [
"running",
"coding"
],
"education": {
"highschool": "N/A",
"college": "Yale"
}
}
You could use following logic to remove elements from your source data:
The recursive function cleanUp() cycles through the data and removes all the entries with values that are set in array $remove
$arr = json_decode($json, true);
$remove = ['N/A', '-','',];
cleanUp($arr, $remove);
function cleanUp(array &$arr, array $remove = [])
{
foreach($arr as $key => &$value) {
if(is_array($value)) {
cleanUp($value, $remove);
} else {
if(in_array($value, $remove)) unset($arr[$key]);
}
}
}
working demo

Acessing specific key/values in nested array in each iteration

I am only interested in keys class and score and their values in my nested array. How can I only get these keys values to be printed out?
This is my $result array.
{ "images": [ { "classifiers": [ { "classifier_id": "default", "name": "default", "classes": [ { "class": "banana", "score": 0.562, "type_hierarchy": "/fruit/banana" }, { "class": "fruit", "score": 0.788 }, { "class": "diet (food)", "score": 0.528, "type_hierarchy": "/food/diet (food)" }, { "class": "food", "score": 0.528 }, { "class": "honeydew", "score": 0.5, "type_hierarchy": "/fruit/melon/honeydew" }, { "class": "melon", "score": 0.501 }, { "class": "olive color", "score": 0.973 }, { "class": "lemon yellow color", "score": 0.789 } ] } ], "image": "fruitbowl.jpg" } ], "images_processed": 1, "custom_classes": 0}
And this is my code logic.
foreach($result as $imgage => $classifier)
{
foreach($classifier["classes"] as $clas)
{
foreach($clas as $key => $value)
{
echo $key . ": " . $value;
}
}
}
This should work for you,
<?php
$string = '{"images":[{"classifiers":[{"classifier_id":"default","name":"default","classes":[{"class":"banana","score":0.562,"type_hierarchy":"/fruit/banana"},{"class":"fruit","score":0.788},{"class":"diet (food)","score":0.528,"type_hierarchy":"/food/diet (food)"},{"class":"food","score":0.528},{"class":"honeydew","score":0.5,"type_hierarchy":"/fruit/melon/honeydew"},{"class":"melon","score":0.501},{"class":"olive color","score":0.973},{"class":"lemon yellow color","score":0.789}]}],"image":"fruitbowl.jpg"}],"images_processed":1,"custom_classes":0}';
$array = json_decode($string,1);
foreach($array['images'] as $key => $images)
{
foreach($images['classifiers'] as $key => $classes)
{
foreach($classes['classes'] as $cls_score){
echo "class = ". $cls_score['class']. " & score = ". $cls_score['score'].PHP_EOL;
}
}
}
WORKING DEMO: https://3v4l.org/vF2RL
Can you try ?
$str = '{ "images": .... }';
// get associative array from json
$result = json_decode($str, true)['images'];
foreach ($result as $imgage => $classifiers) {
foreach ($classifiers["classifiers"] as $classifier) {
foreach ($classifier["classes"] as $clas) {
foreach ($clas as $key => $value) {
// you can add condition here to target only desired keys
echo $key . ": " . $value;
}
}
}
}

get multidimension array key value to single array php

{
"list": [
{
"id": 62,
"user_id": "34",
"updated_at": "2017-10-15 08:24:32",
"request": {
"data": "yes",
"watch": "Pending"
}
},
{
"id": 63,
"user_id": "34",
"updated_at": "2017-10-15 08:24:32",
"request": {
"data": "yes",
"watch": "Yes"
}
}, ]
}
How can i get the watch value to under the updated_at
As Expected
"list": [
{
"id": 62,
"user_id": "34",
"updated_at": "2017-10-15 08:24:32",
"watch": "Pending"
}..
I tried using array_column but doesn't work for me.
function array_column($array, $column){
$ret = array();
foreach($array as $row){
$ret[] = $row[$column];
return $ret;
}
}
Somewhat like
function updateArray(&$array){
foreach($array['list'] as $key => $item){
$array['list'][$key]['watch'] = $item['request']['watch'];
unset($array['list'][$key]['request']);
}
}
updateArray($array);
print_r($array);
Demo
I assume that you know that you need to decode the JSON first:
$array = json_decode($json, true);
Then access the array under the list element:
$result = array_column($array['list'], 'updated_at');
It was a good challenge.here you are
<pre>
<?php
$array=array("list"=>array(array("id"=>"62","user_id"=>"32","updated_at"=>2017,"request"=>array("data"=>"yes","watch"=>"panddin")),
array("id"=>"60","user_id"=>"30","updated_at"=>2016,"request"=>array("data"=>"no","watch"=>"pan"))));
//print_r($array);
foreach($array as $row){
foreach ($row as $key => $value){
if((is_array($value))){
foreach ($value as $key1 => $k){
if((is_array($k))){
foreach ($k as $key2 => $value2) {
echo $key2."=>". $value2."<br>";
}
}else echo $key1."=>".$k."<br>";
}
}else echo $key."=>".$value. "<br>";
}
}
?>
</pre>

php - Getting JSON values from key names

I have a JSON similar to the following:
{
"name": "Activities",
"description": "Activities",
"parent_group_id": 0,
"display": "Activities",
"group_id": 7,
"stamps": [
{
"stamp_id": 14,
"name": "Stamp 14",
"rank": 2
},
{
"stamp_id": 20,
"name": "Stamp 20",
"rank": 4
}
]
},
{
"name": "Games",
"description": "Games",
"parent_group_id": 0,
"display": "Games",
"group_id": 6,
"stamps": [
{
"stamp_id": 33,
"name": "Stamp 33",
"rank": 3
},
{
"stamp_id": 31,
"name": "Stamp 31",
"rank": 1
}
]
}
I want to get a list of each of the stamp_ids seperated by commas through PHP (eg. 14,20,33,31)
I have already tried this, with no luck:
$stampsdata = json_decode($stampsjson, true);
$numberofstamps = $stampsdata['stamps']['stamp_id']);
Can anyone help?
decode the JSON with json_decode and use array_column to get the IDs.
working solution:
// true needed to transform object to associative array
// $json contains your JSON string
$data = json_decode($json, true);
$stamps = [];
foreach ($data as $obj) {
$stamps[] = array_column($obj['stamps'], 'stamp_id');
}
// implode sub arrays and concatenate string
$str = '';
foreach ($stamps as $stamp) {
$sub = implode(',', $stamp);
$str .= $sub . ',';
}
// remove trailing comma
$stampIds = rtrim($str, ',');
print ($stampIds);

Looping through an array in PHP not working as expected

I am retrieving the following array, which is the options list for a product, using the bigCommerece API. Using echo $curlProductOptions I see the following echoed to the screen:
[
{
"id": 412,
"option_id": 37,
"display_name": "testSteveMemory",
"sort_order": 0,
"is_required": true
},
{
"id": 413,
"option_id": 34,
"display_name": "Hard Drive (desktop)",
"sort_order": 1,
"is_required": true
},
{
"id": 414,
"option_id": 24,
"display_name": "Include Keyboard & Mouse",
"sort_order": 2,
"is_required": true
},
{
"id": 415,
"option_id": 33,
"display_name": "Memory",
"sort_order": 3,
"is_required": true
}
]
So I am presuming I have an array within $curlProductOptions containing the above data.
I now need to loop through each element and echo each 'option_id'.
I have tried :
foreach($curlProductOptions['option_id'] as $value)
{echo $value;}
and:
for ($i = 0; $i < count($curlProductOptions); ++$i)
{echo 'optionID ='.$curlProductOptions[$i].option_id.'<br>';}
I also tried just to echo one of the elements.
echo $curlProductOptions['option_id'][0];
echo $curlProductOptions[0]['option_id'];
What am I not understanding here?
You have json encoded string. So you need to json_decode first .
try like this:
$curlProductOptions = json_decode($curlProductOptions,true);//create associative array
foreach($curlProductOptions['option_id'] as $value){
echo $value;
}
This works fine for me:
$curlProductOptions = json_decode($curlProductOptions, true);
foreach($curlProductOptions as $value){
echo $value['option_id'];
}

Categories