JSON Delet value - php

[
{
"1":{
"a":"blablabla",
"b":"...",
"c":"..",
"e":"..."
},
"2":{
"a":"blablabla",
"b":"...",
"c":"..",
"e":"..."
},
"3":{
"a":"blablabla",
"b":"...",
"c":"..",
"e":"..."
}
}
]
desired result :
[
{
"1":{
"a":"blablabla",
"b":"...",
"c":"..",
"e":"..."
},
"3":{
"a":"blablabla",
"b":"...",
"c":"..",
"e":"..."
}
}
]
hi,
I have a JSON that looks like this, I would like to be able to delete data 2 for example ( with a b c e ), anyone to help me?
I tried a lot of things but it always ends up deleting everything.
I found this which seems to show me the right way, but I can't adapt the code.
$data = file_get_contents('teste_data.json');
$json_arr = json_decode($data, true);
$arr_index = array();
foreach ($json_arr as $key => $value) {
if ($value['YOUR KEY'] == SOME VALUE TO COMPARE) {
$arr_index[] = $key;
}
}
foreach ($arr_index as $i) {
unset($json_arr[$i]);
}
$json_arr = array_values($json_arr);
file_put_contents('teste_data.json', json_encode($json_arr));
I want to retrieve the value deleted with a GET, but then I don't know how to delete only this one

You have an array level you are not taking into account
Here is the array:
Array
(
[0] => Array (
[1] => Array (
[a] => blablabla
[b] => ...
[c] => ..
[e] => ...
)
[2] => Array (
[a] => blablabla
[b] => hello
[c] => ..
[e] => ...
)
[3] => Array (
[a] => blablabla
[b] => ...
[c] => ..
[e] => ...
)
)
)
So, see comments to find the changes
$data = file_get_contents('teste_data.json');
$json_arr = json_decode($data, true);
$arr_index = array();
foreach ($json_arr[0] as $key => $value) {
// change ^^^
if ($value['b'] == 'SOME VALUE TO COMPARE') {
$arr_index[] = $key;
}
}
foreach ($arr_index as $i) {
unset($json_arr[0][$i]);
// change ^^^
}
$json_arr = array_values($json_arr);
file_put_contents('teste_data.json', json_encode($json_arr));

Since you changed your desired result, here is the original answer and the modified one:
Remove the key's in the object:
<?php
$delete = ["a", "c"];
$json = json_decode(file_get_contents('teste_data.json'), true);
foreach ($json[0] as $key => $array) {
foreach ($delete as $value) {
if (array_key_exists($value, $array)) {
unset($array[$value]);
}
}
$json[$key] = $array;
}
file_put_contents('teste_data.json', json_encode(array_values($json)));
Remove the keys in the array:
<?php
$delete = [1, 3];
$json = json_decode(file_get_contents('teste_data.json'), true);
foreach ($delete as $value) {
if (array_key_exists($value, $json[0])) {
unset($json[$value]);
}
}
file_put_contents('teste_data.json', json_encode(array_values($json)));

Related

PHP delete json element

the json data is
[name] => stdClass Object
(
[first] => Andy
[middle] =>
[last] => James
)
[age] => 18
[lovely] => Array
(
[0] => running
[1] => coding
[2] => -
)
I need to delete [lovely][2] because that's no answer, but I write this code, it's not working...
$keysToRemove = array("N/A", "-", "");
// Recursively iterate through object and remove keys with specified values
function cleanObject($obj) {
foreach ($obj as $key => $value) {
if (is_object($value) || is_array($value)) {
$obj->$key = cleanObject($value);
} else {
if (in_array($value, $GLOBALS['keysToRemove'])) {
unset($obj->$key);
}
}
}
//print_r($obj);
return $obj;
}
the output is
{"name":
{"first":"Andy","last":"James"},"age":18,
"lovely":["running","coding","-"]}
it's error.
the correct output is
{"name":{"first":"Andy","last":"James"},"age":18,
"lovely":["running","coding"]}
how can delete "-"??
As "lovely" key is an Array and not an Object, you can't use Array->Property expression like you do in case of Object. For this purpose, add following block to your code:
$string = '{"name": {"first": "Andy", "middle": "", "last": "James"}, "age": "18", "lovely": ["running", "coding", ""]}';
$json = json_decode($string);
$keysToRemove = array("N/A", "-", "");
function cleanObject ($obj) {
foreach ($obj as $key => $value) {
if (is_object($value) || is_array($value)) {
$obj->$key = cleanObject($value);
} else {
if (in_array($value, $GLOBALS['keysToRemove'])) {
if (is_array($obj)) {
unset($obj[$key]);
} else {
unset($obj->$key);
}
}
}
}
return $obj;
}
var_dump(cleanObject($json));

Convert PHP array to specific JSON data

I have trying to generate specific json for Rubrics which require this below format only .
Why I need this ?
https://surveyjs.io/Examples/Library?id=questiontype-matrix-rubric&platform=jQuery&theme=bootstrap#content-js
For surveyJS it i am creating cells json using PHP
PHP output
Array
(
[Attendance] => Array
(
[0] => Array
(
[OUTSTANDING] => A
)
[1] => Array
(
[Satisfactory] => B
)
[2] => Array
(
[Needs Improvement] => C
)
[3] => Array
(
[Unacceptable] => D
)
)
[Punctuality] => Array
(
[0] => Array
(
[OUTSTANDING] => A
)
[1] => Array
(
[Satisfactory] => B
)
[2] => Array
(
[Needs Improvement] => C
)
[3] => Array
(
[Unacceptable] => D
)
)
)
Output I have been trying to achieve and required
{
"Attendance": {
"OUTSTANDING": "A",
"Satisfactory": "B",
"Needs Improvement": "C",
"Unacceptable": "D"
},
"Punctuality": {
"OUTSTANDING": "A",
"Satisfactory": "B",
"Needs Improvement": "C",
"Unacceptable": "D"
}
}
This is what I have tried so far :-
$finalArr = [];
$columns = [];
$rows = [];
$cells = [];
$rubics = json_decode($model->rubric_json);
$points = json_decode($model->points_json);
$rubicsCols = json_decode($model->rubric_json);
if (!empty($rubicsCols[0])) {
$columns = array_filter($rubicsCols[0], 'strlen');
}
if (!empty($points[0])) {
$points = array_filter($points[0], 'strlen');
}
unset($rubics[0]);
if (!empty($rubics)) {
foreach ($rubics as $key => $data) {
$rows[] = [
'value' => $data[0],
'text' => $data[0]
];
}
}
if (!empty($rows)) {
foreach ($rows as $rowKey => $row) {
foreach ($columns as $key => $column) {
$cells[$row['text']][] =[
$column =>$rubics[$rowKey + 1][$key]
] ;
}
}
}
echo "<pre>";
print_r(json_encode($cells,JSON_PRETTY_PRINT));exit;
after json_encode($cells,JSON_PRETTY_PRINT) output is :-
{
"Attendance": [
{
"OUTSTANDING": "Attends all of class.Never arrives late, leaves early, or is in and out of the class while it is in progress."
},
{
"Satisfactory": "Attends most of class.Rarely arrives late, leaves early, or is in and out of the class while it is in progress."
},
{
"Needs Improvement": "Sometimes absent.Sometimes arrives late, leaves early, or is in and out of the class while it is in progress."
},
{
"Unacceptable": "Often absent.Often arrives late, leaves early, or is in and out of the class while it is in progress."
}
],
"Punctuality": [
{
"OUTSTANDING": "Always ready to start when class starts at the beginning of the day and when class resumes after breaks."
},
{
"Satisfactory": "Usually ready to start when class starts at the beginning of the day and when class resumes after breaks."
},
{
"Needs Improvement": "Rarely ready to start when class starts at the beginning of the day and when class resumes after breaks."
},
{
"Unacceptable": "Almost never ready to start when class starts at the beginning of the day and when class resumes after breaks"
}
]
}
You need to flatten each sub-array. Given that structure this should work:
foreach($array as $key => $val) {
$array[$key] = array_merge(...$val);
}
If you have an old PHP version then:
$array[$key] = call_user_func_array('array_merge', $val);
According to json.org specification an associative array will be converted to an object and flat one will be an array, so you need something like:
<?php
$arr = [
'Attendance' => [
'OUTSTANDING' => 'A',
'Satisfactory' => 'B',
'Needs Improvement' => 'C',
'Unacceptable' => 'D'
],
'Punctuality' => [
'OUTSTANDING' => 'A',
'Satisfactory' => 'B',
'Needs Improvement' => 'C',
'Unacceptable' => 'D'
]
];
echo '<pre>';
echo json_encode($arr, JSON_PRETTY_PRINT);

Find highest value entry in sub array using JSON & PHP

I have been playing around with this for a few hours now and have had not much luck.
My current JSON looks like this:
https://pastebin.com/TSmWFA2g
"10-10-2019 12:00AM":[
{
"speed":33,
"latitude":-11.2588112,
"longitude":100.8249533
},
{
"speed":33,
"latitude":-11.2381112,
"longitude":100.82509
},
{
"speed":31,
"latitude":-11.827312,
"longitude":100.8242733
}
],
"10-10-2019 12:01AM":[
{
"speed":29,
"latitude":-11.2902112,
"longitude":100.8202849
},
{
"speed":26,
"latitude":-11.2826432,
"longitude":100.3760333
}
]
What I am attempting to do is for each date find the entry that has the highest "speed" and remove the other entries under that date (or create a new array with the single entry).
EDIT 01:
I have now tried:
function my_sort($a,$b)
{
return $b['speed'] - $a['speed'];
}
usort($finalData,"my_sort");
echo json_encode($finalData);
This sorts the data by speed but the JSON now does not include the date found in the original JSON.
[{"speed":33,"latitude":-11.2588112,"longitude":100.82509},
{"speed":33,"latitude":-11.2588112,"longitude":100.82509},
{"speed":31,"latitude":-11.2588112,"longitude":100.82509},
{"speed":31,"latitude":-11.2588112,"longitude":100.82509},
{"speed":33,"latitude":-11.2588112,"longitude":100.82509},
{"speed":32,"latitude":-11.2588112,"longitude":100.82509},
{"speed":24,"latitude":-11.2588112,"longitude":100.82509},
{"speed":16,"latitude":-11.2588112,"longitude":100.82509},]
<?php
$data = json_decode('{
"10-10-2019 12:00AM":[
{
"speed":33,
"latitude":-11.2588112,
"longitude":100.8249533
},
{
"speed":33,
"latitude":-11.2381112,
"longitude":100.82509
},
{
"speed":31,
"latitude":-11.827312,
"longitude":100.8242733
}
],
"10-10-2019 12:01AM":[
{
"speed":29,
"latitude":-11.2902112,
"longitude":100.8202849
},
{
"speed":26,
"latitude":-11.2826432,
"longitude":100.3760333
}
],
"10-10-2019 12:02AM":[
{
"speed":35,
"latitude":-11.2991112,
"longitude":100.0129199
},
{
"speed":33,
"latitude":-11.9273112,
"longitude":100.8734016
},
{
"speed":32,
"latitude":-11.2533212,
"longitude":100.19229
},
{
"speed":30,
"latitude":-11.2928112,
"longitude":100.2495099
},
{
"speed":24,
"latitude":-11.2228112,
"longitude":100.9266033
}
]
}',true);
$newArray=array();
foreach ($data as $key => $value) {
array_multisort(array_column($value, 'speed'), SORT_DESC, $value);
$newArray[$key]=$value[0];
}
echo "<pre>";
print_r($newArray);
echo "<pre>";
?>
$max = []; //store highest speeds in new array
foreach ($json as $key => $obj) {
$max[$key] = max(array_map(function($o) {
return $o;
}, $obj));
}
Working sample: http://sandbox.onlinephpfunctions.com/code/2f6e1a86775e206650bfe86f7602464c0fce17f0
As you just want the highest for each date, this code just loops round each item and stores the one with the highest speed for the date, if there are multiple ones with the same speed, the first is taken. This saves having to sort the arrays and then chop them up and makes 1 pass through the data...
$output = [];
$input = json_decode($data, true);
foreach ( $input as $date => $dateSection ) {
$max = ["speed" => 0];
foreach ( $dateSection as $item ) {
if ( $item["speed"] > $max["speed"] ) {
$max = $item;
}
}
$output[$date] = $max;
}
print_r($output);
this gives the output...
Array
(
[10-10-2019 12:00AM] => Array
(
[speed] => 33
[latitude] => -11.2588112
[longitude] => 100.8249533
)
[10-10-2019 12:01AM] => Array
(
[speed] => 29
[latitude] => -11.2902112
[longitude] => 100.8202849
)
[10-10-2019 12:02AM] => Array
(
[speed] => 35
[latitude] => -11.2991112
[longitude] => 100.0129199
)
)

How to merge array multi key to single array

I have a array multi level
$array = array("14529" => array("900" => array("87" => array() ) ) );
print_r(array_keys($array)); // result array("14529");
How to merge this array to single array
$array = array("14529", "900", "87");
Here is a function that does what you want. It is done recursively, so it doesn't matter how deep the array is.
function mergeArrayMultiKeyToSingleArray($array, $result=[])
{
foreach($array as $key => $value) {
$result[] = $key;
if(is_array($value)) {
$result = mergeArrayMultiKeyToSingleArray($value, $result);
}
}
return $result;
}
// USAGE:
$array = array("14529" => array("900" => array("87" => array() ) ) );
$array = mergeArrayMultiKeyToSingleArray($array);
// $array is now ["14529", "900", "87"]
The solution using RecursiveIteratorIterator class:
$arr = ["14529" => ["900" => ["87" => [] ] ] ];
$keys = [];
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($arr), RecursiveIteratorIterator::SELF_FIRST) as $k => $v) {
$keys[] = $k;
}
print_r($keys);
The output:
Array
(
[0] => 14529
[1] => 900
[2] => 87
)
I did this using class
class ArrayStripper
{
private $items = [];
public function strip($arrayOrItem)
{
if(is_array($arrayOrItem))
{
foreach ($arrayOrItem as $item)
{
$this->strip($item);
}
}
else
{
$this->items[] = $arrayOrItem;
}
}
public function get()
{
return $this->items;
}
}
$array = [1 , [2,3] , 4 , [[5 , 6 , 7] , [8 ,9] , 10]];
$stripper = new ArrayStripper();
$stripper->strip($array);
var_dump($stripper->get());

Prepend key value to array - PHP

I have the below code in a for..loop is there a way I can add values to the beginning of the array?
$data = array();
$initial = strtotime('11:00:00');
for (; $initial < strtotime("23:00:59"); $initial = strtotime("+15 minutes", $initial)) {
if ($initial > strtotime("+45 minutes", time())) {
$row['value'] = date('Hi', $initial);
$row['label'] = date('H:i', $initial);
$data['data'][] = $row;
}
}
I want to add the below values to the top of the array. I have tried using array_unshift but I don't think it supports key-value pairs.
if(!isBetween('22:00', '09:59', date('H:i'))) {
$row['value'] = "asap";
$row['label'] = "ASAP";
}
My array output
{
"data": [
{
"value": "1145",
"label": "11:45"
}
]
}
I want to get this
{
"data": [
{
"value": "asap",
"label": "ASAP"
},{
"value": "1145",
"label": "11:45"
},
]
}
Un-shift should work if you pass the arguments correctly:
array_unshift($data["data"], $prepend);
Alternatively, you could use array_merge, like this:
$data["data"] = array_merge(array($prepend), $data["data"]);
With the following example data:
$data = [
"data" => [
[
"value" => "1145",
"label" => "11:45"
]
]
];
$prepend = [
"value" => "asap",
"label" => "ASAP"
];
$data["data"] = array_merge(array($prepend), $data["data"]);
print_r($data);
You would get this output (with both solutions):
Array (
[data] => Array (
[0] => Array (
[value] => asap
[label] => ASAP
)
[1] => Array (
[value] => 1145
[label] => 11:45
)
)
)
If you need to prepend something to the array without the keys being reindexed and/or need to prepend a key value pair, you can use this short function:
function array_unshift_assoc(&$arr, $key, $val) {
$arr = array_reverse($arr, true);
$arr[$key] = $val;
return array_reverse($arr, true);
}
Source: http://php.net/manual/en/function.array-unshift.php

Categories