how to delete specific index with comparing - php

i want to delete some index with comparing but it is not easy
first one our php version is 5
for example my result is like this
it is echo by json_encode and it was array
and the data is dynamic
[
{
"idx": "1",
"mom_member_idx": "1",
"teacher_member_idx": "2",
"care_start_datetime": "2019-09-09 08:30:00",
},
{
"idx": "2",
"mom_member_idx": "1",
"teacher_member_idx": "2",
"care_start_datetime": "2019-09-10 08:30:00",
},
{
"idx": "3",
"mom_member_idx": "2",
"teacher_member_idx": "2",
"care_start_datetime": "2019-09-09 08:30:00",
}
]
and i want to result like this comparing and unset with the latest one
[
{
"idx": "1",
"mom_member_idx": "1",
"teacher_member_idx": "2",
"care_start_datetime": "2019-09-09 08:30:00",
},
{
"idx": "3",
"mom_member_idx": "2",
"teacher_member_idx": "2",
"care_start_datetime": "2019-09-09 08:30:00",
}
]
i tried like this but it is not work
while ($r = mysqli_fetch_assoc($chat_list)) {
$dbdata[] = $r;
}
for($r=0;$r<sizeof($dbdata);$r++){
if ($dbdata[$r]['mom_member_idx']+$dbdata[$r]['teacher_member_idx']==$dbdata[$r+1]['mom_member_idx']+$dbdata[$r+1]['teacher_member_idx'])
{
if($dbdata[$r]['care_start_datetime']<$dbdata[$r+1]['care_start_datetime']){
unset($dbdata[$r]);
}else {
unset($dbdata[$r+1]);
}
}
}

First, convert your JSON array into a PHP array. then you can remove the array elements using the array index
$someArray = json_decode($someJSON, true);

You can sort the data by descending order by care_start_datetime using usort() and unset the first index form that sorted data.
Code example:
$data = json_decode('[
{"idx": "1","mom_member_idx": "1","teacher_member_idx": "2","care_start_datetime": "2019-09-09 08:30:00"},
{"idx": "2","mom_member_idx": "1","teacher_member_idx": "2","care_start_datetime": "2019-09-10 08:30:00"},
{"idx": "3","mom_member_idx": "2","teacher_member_idx": "2","care_start_datetime": "2019-09-09 08:30:00"}
]', true);
usort($data, function($a, $b) {
return strtotime($a['care_start_datetime']) > strtotime($b['care_start_datetime']) ? -1 : 1;
});
unset($data[0]);
print_r($data);
Working demo.

Your variant with summing to columns is not totally correct, because sum of some integers give you wrong result and you can accidentally remove the wrong one. Like 2 + 3 == 1 + 4 not correct.
Maybe that code helps you:
$groupedData = array();
while ($r = mysqli_fetch_assoc($chat_list)) {
// We create unique key for group same rows
// (with the same 'mom_member_idx' and 'teacher_member_idx')
$uniqueKey = implode('_', [$r['mom_member_idx'], $r['teacher_member_idx']]);
if (!array_key_exists($uniqueKey, $groupedData)) {
$groupedData[$uniqueKey] = array();
}
// Add row to grouped array by our unique key
$groupedData[$uniqueKey][] = $row;
}
$result = array();
foreach ($groupedData as $rows) {
// If in grouped array with that unique key only one row - just add it
if (count($rows) <= 1) {
$result[] = $rows[0];
continue;
}
// Go for all same rows and check date
$neededRow = null;
foreach ($rows as $row) {
// Here I don't understand what kind of date do you want - minimum or maximum
// You just can reverse the sign
if (
is_null($neededRow) ||
strtotime($row['care_start_datetime']) > strtotime($neededRow['care_start_datetime'])
) {
$neededRow = $row
}
}
if ($neededRow) {
$result[] = $neededRow;
}
}

For delete specific index first you need to convert JSON array into PHP array using json_decode() function, once you convert it into PHP array you can remove specific index using key,
foreach ($data as $key => $element) {
$value = $element['...'];
if (...) {
unset($data[$key]);
// or
$data[$key]['...'] = '...';
}
}
Hope this helps you.

Related

Group PHP array values based on 2 sub-values

I have called a JSON array from an API and used json_decode to assign them to a PHP variable.
The array looks like this:
[
{
"id": "1",
"abbr": "XXX",
"title": "YYY",
"visible_from_lat": "85",
"visible_to_lat": "-75",
},
{
"id": "2",
"abbr": "AAA",
"title": "BBB",
"visible_from_lat": "85",
"visible_to_lat": "-75",
}
]
The array has approx 50 items in total, all of which have a visible_from_lat and a visible_to_lat. What I need to do is group each items like so:
visible_from_lat > 0 then assign to variable1
visible_from_lat < 0 then assign to variable2
Any idea's how I do this?
Here there is a basic solution, assuming that in data.json file there are your json data:
<?php
$array = json_decode(file_get_contents("data.json"));
$resulSetPositive = [];
$resulSetNegative = [];
foreach ($array as $obj) {
if(isset($obj->visible_from_lat)) {
if($obj->visible_from_lat > 0) {
$resulSetPositive[] = $obj; // add obj to positive result set
}
else if($obj->visible_from_lat < 0) {
$resulSetNegative[] = $obj; // add obj to negative result set
}
}
}
file_put_contents("negative.json", json_encode($resulSetNegative, JSON_PRETTY_PRINT));
file_put_contents("positive.json", json_encode($resulSetPositive, JSON_PRETTY_PRINT));

How to take a value from nested array(json format) without using multiple foreach in php

I want to take the all id values in the json format.
{
"1": {
"name": "test",
"followup": {
"1": {
"id": "98",
"followup": {
"1": {
"id": "93",
"followup": {
"1": {
"id": "174"
},
}
}
}
}
}
}
}
I can achieve this by using nested foreach. But now the 'followup' key is present in 3 but it may came 6,7 so we can't add 6,7 foreach.
You can use the array_walk_recursive() for this, like(DEMO):
$ids = array();
$data = json_decode($str, true);
array_walk_recursive($data, function($v, $k) use (&$ids) {
if ($k === 'id') {
$ids[] = $v;
}
});
var_dump($ids);
This basically goes through every index 1 at a time and matches the the keys against the key id, and if it matches it captures the value.

PHP - object array into json

array of $setting['accountType'] :
$setting['accountType']['all'] = 'ALL';
$setting['accountType']['A1'] = 'VIP1';
$setting['accountType']['A2'] = 'VIP2';
PHP code to generate the object:
$object = new stdClass();
$myArray = array();
foreach ($setting['accountType'] as $key => $val)
{
$object->id = $key;
$object->desc = $val;
$myArray[] = $object;
}
$accountType = $myArray;
PHP code to format object into json:
json_encode(['accountType'=> [(object)$accountType]));
However, i get the output as below :
"accountType": [{
"0": {
"id": "A2",
"desc": "VIP"
},
"1": {
"id": "A2",
"desc": "VIP"
},
"2": {
"id": "A2",
"desc": "VIP"
}
}]
Problem 1: why $accountType only keep the last object when I loop through?
Problem 2: without the array key of $accountType [solved by using array_values($accountType)]
This is something that I am trying to achieve:
"accountType": [{
"id": "all",
"desc": "All "
}, {
"id": "A1",
"desc": "Normal"
}, {
"id": "A2",
"desc": "VIP"
}]
How to get the output as above?
You should use
json_encode(['accountType'=> $accountType]);
instead of
json_encode(['accountType'=> [(object)$accountType]]);
In your code you are putting $accountType inside another array that is why you are getting that result
Here is a Demo and Explanation
Edit: The entire code
$setting['accountType']['all'] = 'ALL';
$setting['accountType']['A1'] = 'VIP1';
$setting['accountType']['A2'] = 'VIP2';
$myArray = array();
foreach ($setting['accountType'] as $key => $val)
{
$object = new stdClass(); // Note: $object should be created inside the loop
$object->id = $key;
$object->desc = $val;
$myArray[] = $object;
}
$accountType = $myArray;
echo json_encode(['accountType'=> $accountType]);
And Here is the Revised Demo
Try this,
echo json_encode(array_values($your_array));
Let me know if its working
This is exactly the same thing, no?
The numerotation is displayed because you need it to access to the specific json object.
You have an array and you can access to each element by its key.

PHP get array items based on string mask

i have an array with a bunch of records like in:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"typeID": "1",
"datein": "2016-09-26 12:14:16",
"edited_datein": null,
"publishDate": "2016-09-23 00:00:00",
"category": {
"ID": "1",
"heading": "News",
"typeID": "3",
"datein": "2016-09-26 11:50:06",
"edited_datein": null,
"url": "news"
},
"authorID": "592",
"tags": "skool,school,hoof,headmaster,etienne burger"
}
i have another array with "columns" i want the records to be "filtered" by
{
"ID",
"heading",
"datein",
"category|heading",
"category|url"
}
i would like the result to create a multidimensional array based on the column items:
{
"ID": "38424",
"heading": "Nylies soek nuwe hoof",
"datein": "2016-09-26 12:14:16",
"category": {
"heading": "News",
"url": "news"
}
}
how do i achieve this? i'm totally stuck on this now :( busy trying a hack of array_combine now but i dont hold much hope it would work out
so after being stuck on this for many hours.. and posting it here. i found a solution
$new_list = array();
foreach ($n as $record) {
$new_list[] = filter_columns($columns, $record);
}
and the function:
function filter_columns($columns, $record, $pre="") {
$return = array();
foreach ($record as $key => $value) { // loop through the fields in the record
$str = $pre.$key; // create a string of the current key
if (in_array($str,$columns)){
$return[$key] = $value;
}
if (is_array($value)){
$return[$key] = filter_columns($columns, $value,$key."|"); // if the value is an array recall the function but prepend the current key| to the key mask
}
}
return $return;
}

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. ");
}
?>

Categories