[
{
"id": "123",
"name": "aaa"
},
{
"id": "567",
"name": "bbb"
},
{
"id": "469",
"name": "ccc"
},
{
"id": "577",
"name": "ddd"
},
{
"id": "388",
"name": "eee"
}
]
How to make a order when json decode?
$data = json_decode($json);
foreach ($data as $row) {
sort($row)?
}
I need all the decode data make an order by id.
Final data output: "name": "aaa", "name": "eee", "name": "ccc", "name": "bbb", "name": "ddd"
You could use usort().
$data = json_decode($json);
usort($data, function($a, $b) {
if ($a->id == $b->id) {
return 0;
}
return $a->id < $b->id ? -1 : 1;
});
Or, if you're using PHP < 5.3, you need to define the comparison function, since the support for anonymous functions was added in PHP 5.3.
function cmp($a, $b) {
if ($a->id == $b->id) {
return 0;
}
return $a->id < $b->id ? -1 : 1;
}
$data = json_decode($json);
usort($data, 'cmp');
This would sort the array. After that, if you want to create an array with only the name values, you could do that with a foreach.
$result = array();
foreach ($data as $entry) {
$result[] = array('name' => $entry->name);
}
The $result variable will now contain:
array(array('name' => 'aaa'),
array('name' => 'eee'),
array('name' => 'ccc'),
array('name' => 'bbb'),
array('name' => 'ddd'));
Then, to encode the result as JSON again, you can call json_encode().
echo json_encode($result);
This will output a string similar to:
[{"name": "aaa"},
{"name": "eee"},
{"name": "ccc"},
{"name": "bbb"},
{"name": "ddd"}]
Related
I have the following JSON object:
{
"id": 1,
"name": null,
"block": {
"type": "none",
"descends": [
{
"operation":"sum",
"descends":[
{
"label":2,
"value":false
}
]
},
{
"label": 1,
"value": 3,
},
{
"label": 2,
"value": 2
}
],
"label": 1,
"value": true
}
}
I want to collect all the label and value attributes and store them in an array, so I created the following function:
public function collectValues($arr){
$finalValues = [];
foreach($arr as $key => $element){
if($key=='block'){
foreach($element as $key2 => $block){
if($key2=='descends'){
foreach($block as $key3 => $node_block){
if($key3=='descends'){
foreach($node_block as $key4 => $anotherNode){
if($key4 == 'descends'){
foreach($anotherNode as $finalNode){
$finalValues [] = array('lable'=>$finalNode->label, 'value' =>$finalNode->value);
}
}
}
}
else{
$finalValues [] = array('lable' => $node_block->label, 'value' => $node_block->value);
}
}
}
}
$finalValues [] = array('lable'=> $element->label, 'value' => $element->value);
}
}
return $finalValues;
}
The function works and I get the following:
[
{
"lable": 2,
"value": false
},
{
"lable": 1,
"value": 3
},
{
"lable": 2,
"value": 2
},
{
"lable": 1,
"value": true
}
]
The problem is that the JSON object can contain more descends like:
{
"id": 1,
"name": null,
"block": {
"type": "none",
"descends": [
{
"operation":"sum",
"descends":[
{
"operation":"sum",
"descends":[
{
"label":2,
"value":false
}
],
"label":2,
"value":false
}
]
},
{
"operation":"sum",
"descends":[
{
"label":2,
"value":false
}
],
"label": 1,
"value": 3,
},
{
"label": 2,
"value": 2
}
],
"label": 1,
"value": true
}
}
This means I will have to add more foreach loops. A good way to handle such a situation is by using recursive. How can I transform the function above into a recursive one?
Your looped function does not make sense to change. Easier to rewrite from scratch
Here is my use case for recursion. Maybe there is an easier option, but I didn’t chase optimization
$array = json_decode($json, true); //in $json your JSON)
$result = []; // array for result
checkLabel($array, $result);
print_r($result);
function checkLabel(array $array, &$result){
//first check every element on nested array
foreach ($array as $key => $value){
if (is_array($value)) {
//if found call recursive function
checkLabel($value, $result);
}
}
//then check 'label' key.. its mean we have attribute
if (array_key_exists('label', $array)) {
//save it
$result[] = [
'label' => $array['label'],
'value' => $array['value']??'' //if have label but without value)
];
}
}
Here is my JSON
[
{
"TIMESTAMP": "2021-06-09 13:13:26",
"COL1": "10",
"COL2": "20",
"COL3": "30"
},
{
"TIMESTAMP": "2021-06-22 13:13:26",
"COL1": "20",
"COL2": "30",
"COL3": "40"
},
{
"TIMESTAMP": "2021-06-21 13:13:26",
"COL1": "1",
"COL2": "2",
"COL3": "3"
},
{
"TIMESTAMP": "2021-06-20 13:13:26",
"COL1": "40",
"COL2": "50",
"COL3": "60"
}
]
I need to refactor the json According to the Column name like (EXPECTED OUTPUT)
[
{
"TITLE":"COL1"
"DATA":[10,20,1,40]
},
{
"TITLE":"COL2"
"DATA":[20,30,2,50]
},
{
"TITLE":"COL3"
"DATA":[30,40,3,60]
},
]
I was tried but it not working
$data = json_decode($result, true);
$refactored = array_map(function($item) {
return (object)[
'TIMESTAMP' => $item['TIMESTAMP'],
'DATA' => [ $item['COL1'], $item['COL2'], $item['COL3'] ]
];
}, $data);
dump($refactored);
Someone help me out with this. The column may be 3 or more and it must be dynamic. Thanks in advance.
You can transform your JSON like this:
$data = json_decode($result, true);
$refactored = array_reduce($json, function($carry, $item) {
foreach($item as $key => $value) {
if (str_starts_with($key, 'COL')) {
$index = substr($key, 3, 1) - 1;
if (!isset($carry[$index])) {
$carry[$index] = [
'Title' => $key
];
}
$carry[$index]['Data'][] = $value;
}
}
return $carry;
}, []);
dump($refactored);
I am always a fan of using the value you want to group your data by as a temporary array key, that makes things easier, and can simply be reset by using array_values afterwards.
$input = json_decode('…', true);
$output = [];
foreach($input as $item) {
foreach($item as $key => $value) {
if($key != 'TIMESTAMP') {
$output[$key]['TITLE'] = $key;
$output[$key]['DATA'][] = (int)$value;
}
}
}
$output = array_values($output);
echo json_encode($output);
All you have to do is re-encode the processed data:
json_encode($refactored) will give you the output that you want.
P.S. you don't have to cast to an object. It works as array as well.
I want to merge two same keys in an array and get the sum of the values.
I want the same structure as it is now.Because this data needs to be converted to JSON.
This is what i get now.
{
"data": [{
"count_of_invites": 5,
"user": "Rajesh",
"id": "53"
},
{
"count_of_invites": 9,
"user": "Student",
"id": "45"
},
{
"count_of_invites": 4,
"user": "Student",
"id": "45"
}
]
}
As you can see the id 45 are repeated.As i want the result as,
Expected output
{
"data": [{
"count_of_invites": 5,
"user": "Rajesh",
"id": "53"
},
{
"count_of_invites": 13,
"user": "Student",
"id": "45"
}
]
}
As you can see the duplicate entry should be removed as well as the count_of_invites of duplicate entry should be added.
<?php
$data = [
[
'id' => 2,
'name' => 'Paul',
'count' => 4
],
[
'id' => 3,
'name' => 'Peter',
'count' => 5
],
[
'id' => 3,
'name' => 'Peter',
'count' => 7
]
];
foreach($data as $array)
$counts[$array['id']][] = $array['count'];
$counts = array_map('array_sum', $counts);
foreach($data as $k => $array)
$data[$k]['count'] = $counts[$array['id']];
$data = array_unique($data, SORT_REGULAR);
print json_encode($data, JSON_PRETTY_PRINT);
Output:
[
{
"id": 2,
"name": "Paul",
"count": 4
},
{
"id": 3,
"name": "Peter",
"count": 12
}
]
You can achieve it this way:
$ids = array();
$output = array();
foreach ($input as $value) {
if (!isset($ids[$value["id"]])) {
$ids[$value["id"]]=$count($output);
$output[]=$value;
} else {
$output[$ids[$value["id"]]]["count_of_invites"] = $value["count_of_invites"];
$output[$ids[$value["id"]]]["user"] = $value["user"];
}
}
The count method was declared as variable and i've added with addition assignment operator.
Thank You for helping.
$ids = array();
$output = array();
foreach ($response as $value) {
if (!isset($ids[$value["id"]])) {
$ids[$value["id"]] = count($output);
$output[] = $value;
}
else {
$output[$ids[$value["id"]]]["count_of_invites"] += $value["count_of_invites"];
$output[$ids[$value["id"]]]["user"] = $value["user"];
}
}
I am trying to create a json object from the data that I get from Ninja Forms that would look like this:
{
"title": "Contact Me",
"fields": [
{
"label": "Name",
"type": "textbox",
"required": "1"
},
{
"label": "Email",
"type": "email",
"required": "1"
}
]
}
I am trying to do so, like this:
$settings = ['label', 'type', 'required'];
$formTitle = Ninja_Forms()->form( 1 )->get()->get_setting('title');
$formFields = Ninja_Forms()->form(1)->get_fields();
$data = ['title' => $formTitle];
foreach ($formFields as $formField) {
$key = $formField->get_setting('key');
foreach ($settings as $setting) {
$data['fields'][$key][][$setting] = $formField->get_setting($setting);
}
}
return $data;
But, the result of that looks like this:
{
"title": "Contact Me",
"fields": {
"name": [
{ "label": "Name" },
{ "type": "textbox" },
{ "required": "1"}
],
"email": [
{ "label": "Email" },
{ "type": "email" },
{ "required": "1" }
],
How can I do this, so that the result looks like the one I have shown above?
I have also tried like this:
foreach ($settings as $setting) {
$data['fields'][] = $formField->get_setting($setting);
}
But, that gave me this kind of result:
{
"title": "Contact Me",
"fields": [
"Name",
"textbox",
"1",
"Email",
"email",
"1",
"Message",
"textarea",
"1",
"Submit",
"submit",
null
]
}
This gave me the wanted result:
foreach ($formFields as $formField) {
$key = $formField->get_setting('key');
foreach ($settings as $setting) {
$object[$setting] = $formField->get_setting($setting);
}
$data['fields'][] = $object;
}
return $data;
One way to look at this is to count the dimensions of the data. In your desired format, the deepest item is:
{ "fields": [ { "label": "Name"
So you have object -> array -> object.
If we indent each array in your code, we have:
$data // outermost array
['fields']
[$key]
[] // innermost array
[$setting] = $value; // key in innermost array
Or if we were to declare it with just one value:
$data = array(
'field' => array(
$key => array(
0 => array(
$setting => $value
)
)
)
);
So you have 4 levels of array, instead of 3.
Comparing to the JSON, taking an array with numeric keys as "array" and one with non-numeric keys as "object", the pattern is object -> object -> array -> object.
So it's the [$key] we need to eliminate, because it's creating an extra object dimension.
But we don't want to increment the key at [] for each item either, so we need to either make our value in advance...
foreach ($settings as $setting) {
$object[$setting] = $formField->get_setting($setting);
}
$data['fields'][] = $object;
...or choose our key in advance:
$i++;
foreach ($settings as $setting) {
$data['fields'][$i] = $formField->get_setting($setting);
}
I have a CSV file like this
first_name,last_name,phone
Joseph,Dean,2025550194
Elbert,Valdez,2025550148
Using this csv-to-json.php from GitHub I get output like this
[{
"first_name": "Joseph",
"last_name": "Dean",
"phone": "2025550194",
"id": 0
}, {
"first_name": "Elbert",
"last_name": "Valdez",
"phone": "2025550148",
"id": 1
}]
This is almost what I want - however instead of
"phone": "2025550194"
I need
"phone": [{
"type": "phone",
"number": "2025550194"
}]
How do I correct this?
If you get the JSON string, then you would of course first convert it to an array with:
$arr = json_decode($json, true);
But probably you already have the array. You then apply this loop to it:
foreach($arr as &$row) {
if (isset($row['phone'])) { // only when there is a phone number:
$row['phone'] = [[ "type" => "phone", "number" => $row['phone'] ]];
}
}
See it run on eval.in.
You can change the csv-to-json.php code with following and you got the output that you want :-
Option 1 :-
// Bring it all together
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
if ($j == 'phone') {
$newArray[$j] = array('type' => $j, 'number' => $d);
} else {
$newArray[$j] = $d;
}
}
Option 2 :-
$json_response = [{
"first_name": "Joseph",
"last_name": "Dean",
"phone": "2025550194",
"id": 0
}, {
"first_name": "Elbert",
"last_name": "Valdez",
"phone": "2025550148",
"id": 1
}];
$result = json_decode($json_response);
$final_result = array();
foreach ($result as $row) {
$row['phone'] = array('type' => 'phone', 'number' => $row['phone']);
$final_result[] = $row;
}
echo json_encode($final_result);
It may help you.