how I should compare my data to an array json - php

I'm having a hard time in comparing day to array
this is my array:
array:2 [
0 => {
"id": 1
"time_in": "08:00:00"
"time_out": "17:00:00"
"days": "["tuesday","thursday","saturday"]"
}
1 => {
"id": 2
"time_in": "09:00:00"
"time_out": "18:00:00"
"days": "["monday","wednesday","friday"]"
}
]
note: days are json data from database
and I have this variable day
$day = 'friday';
I just want to get the array data with 'friday' in their days
please help me on my code I just don't know how I should manipulate it
or what code I will use to get it
I expect to have this output:
$day = 'friday';
1 => {
"id": 2
"time_in": "09:00:00"
"time_out": "18:00:00"
"days": "["monday","wednesday","friday"]"
}
because it has friday in its day

you can use in_array() function, which searches an array for a specific value.
for search $day="friday", i declare another array as $b and put filtering value into it.
Try this:
$array = array(array("id"=>"1","time_in"=>"08:00:00","time_out"=>"17:00:00","days"=>'["tuesday","thursday","saturday"]'),
array("id"=>"2","time_in"=>"09:00:00","time_out"=>"18:00:00","days"=>'["monday","wednesday","friday"]'));
$day = "friday";
$b = array();
foreach ($array as $val) {
if (in_array($day,$val['days'])) {
$b[] = $val;
}
}
print_r($b);

let's say that your JSON data is defined as $json:
$json_array = json_decode($json);
$result = [];
foreach($json_array as $arr){
if(in_array($day,$arr->days)){
$result[] = $arr;
}
}

use in_array to find data in array
foreach($your_array as $obj){
if(in_array($day, $obj->days)){
return $obj;
}
}

<?php
// the day you want
$day = 'friday';
// decode json to php array
$days = json_decode($yourJSONArrayFromDatabase, true);
for ($i=0; $i < count($days); $i++)
{
if (in_array($day, $days[$i]['days'])) {
echo json_encode($days[$i]);
break;
}
}

Related

PHP - get closest date from array

I want to get closest date from $search_date if is not same values in $array['date']. If is same value in $array['date'] I want all array.
Format date is 'Y-m-d'.
Example 1:
$search_date = '2022-12-08';
$array = [{"price":"200","date":"2022-12-12"},{"price":"50","date":"2022-12-10"},{"price":"100","date":"2022-12-10"}]
Return should be: [{"price":"50","date":"2022-12-10"},{"price":"100","date":"2022-12-10"}]
Example 2:
$search_date = '2022-12-08';
$array = [{"price":"200","date":"2022-12-08"},{"price":"50","date":"2022-12-09"},{"price":"100","date":"2022-12-11"}]
Return should be: [{"price":"200","date":"2022-12-08"}]
Example 3:
$search_date = '2022-12-08';
$array = [{"price":"200","date":"2022-12-10"},{"price":"100","date":"2022-12-10"},{"price":"50","date":"2022-12-11"}]
Return should be: [{"price":"200","date":"2022-12-10"},{"price":"100","date":"2022-12-10"}]
Example 4:
$search_date = '2022-12-08';
$array = [{"price":"200","date":"2022-12-08"},{"price":"100","date":"2022-12-08"},{"price":"50","date":"2022-12-08"}]
Return should be: [{"price":"200","date":"2022-12-08"},{"price":"100","date":"2022-12-08"},{"price":"50","date":"2022-12-08"}]
Thank you!
This code calculates the distance in days between $search and each record. It assumes that you want to find closest distance in both future and past.
<?php
/*
Question Author: Catalin Iamandei
Question Answerer: Jacob Mulquin
Question: PHP - get closest date from array
URL: https://stackoverflow.com/questions/74598442/php-get-closest-date-from-array
Tags: php, arrays, laravel, date, php-carbon
*/
$search = '2022-12-10';
$searchObj = new DateTime($search);
$records = json_decode('[{"price":"200","date":"2022-12-10"},{"price":"100","date":"2022-12-10"},{"price":"50","date":"2022-12-11"}]', true);
$distances = [];
foreach ($records as $index => $record) {
$recordObj = new DateTime($record['date']);
$daysDiff = $searchObj->diff($recordObj)->format("%r%a");
$distances[$index] = abs($daysDiff);
}
$minimumDiff = min($distances);
$output = [];
foreach ($distances as $index => $distance) {
if ($distance == $minimumDiff) {
$output[] = $records[$index];
}
}
echo json_encode($output, JSON_PRETTY_PRINT);
Yields:
[
{
"price": "50",
"date": "2022-12-09"
},
{
"price": "100",
"date": "2022-12-11"
}
]
If you only want to search for closest dates in the future, you need to remove the abs() function and then remove all negative entries in the $distances array before using min().
If you want to search for a specific value in your array have you tried
array_search($value, $array);
By this you can search for a specific value in your array
If you want to search the lowest value
try to for looping your array and check if the array is lower than the previous index and if the for loop has ended you have the lowest date
$lowest_date = null;
for ($i = 0; count($i); $i++) {
if ($array['date'] < $lowest_date) {
$lowest_date = $array['date'];
}
}
you dont have mentioned what todo with prior dates, eg. searching for '2022-12-07', how to tread 2022-12-06 and 2022-12-08, as the difference both is 1. You can calculate the datediff for each entry, get the min datediff and output elements with this datediff. eg :
<?php
$SearchDate = new DateTimeImmutable('2022-12-08');
$array = array ('{"price":"200","date":"2022-12-12"}',
'{"price":"50","date":"2022-12-10"}',
'{"price":"100","date":"2022-12-10"}');
$laResult = array();
foreach($array as $jsonO) {
$json = json_decode($jsonO);
$CompareDate = new DateTimeImmutable($json->{'date'});
$interval = date_diff($SearchDate, $CompareDate);
$laThis['date'] = $json->{'date'};
$laThis['diff'] = $interval->format('%a');
$laThis['origin'] = $jsonO;
$laResult[] = $laThis;
}
$min_diff = min( array_column( $laResult, 'diff') );
echo 'nearestDiff:'. $min_diff .PHP_EOL;
foreach($laResult as $laSingleResult) {
if($laSingleResult['diff'] == $min_diff) {
echo $laSingleResult['origin'] .PHP_EOL;
}
}

How to get the nearest expiration date,

I have this array string :
[
{"expiration": "0000-00", "quantity": -50},
{"expiration": "2023-02", "quantity": 100},
{"expiration": "2022-03", "quantity": 50}
]
how to get the nearest expiration date, means here I need to get the third one 2022-03 and ignore others & also ignore the date that comes with 0000-00
my code:
$minDate = "";
foreach (json_decode($row['items']) as $item) {
if ($item->expiration != "0000-00") {
$minDate = min($item->expiration);
}
}
dd($minDate);
You can try something like this: -
$arr = getNearestExp($row['items']);
print_r($arr);
/**
*To get the Nearest Expiration date
*#input json array of expiration & quantity as
*per the question
*/
function getNearestExp($items){
$items = json_decode($items); // convert the items to json object
$itemArr = [];
foreach($items as $item) {
// exclude the '0000-00' expiration
if($item->expiration != '0000-00'){
$itemArr[strtotime($item->expiration)] = (array)$item;
}
}
// sort the out put array to ASC order to get the smallest value 1st
ksort($itemArr);
// Re indexing the array to proper index keys
$itemArr= array_values($itemArr);
// return the first value of the array
return $itemArr[0];
}
min(), require two values (or more) and return the lowest value. In your case you gave only one. Then, min() cannot compare strings.
You can use several arrays functions such as array_column(), array_filter(), sort() and reset() (Less verbose, but could be less efficient with large data) to achieve this :
$data = json_decode('[
{"expiration": "0000-00", "quantity": -50},
{"expiration": "2023-02", "quantity": 100},
{"expiration": "2022-03", "quantity": 50}
]');
// extract 'expiration', remove '0000-00'
$data = array_filter(array_column($data, 'expiration'), fn($item) => $item != '0000-00');
sort($data);
var_dump(reset($data)); // string(7) "2022-03"
demo (3v4l.org)
Here is another way.
<?php
//Enter your code here, enjoy!
$json = "[{\"expiration\": \"0000-00\", \"quantity\": -50},{\"expiration\": \"2023-02\", \"quantity\": 100},{\"expiration\": \"2022-03\", \"quantity\": 50}]";
$array = json_decode($json);
$currentDate = date_create_from_format('Y-m-d', date("Y-m-d"));
$daysDiff = 365;
$nearest = "";
for($i = 0; $i<count($array); $i ++) {
$v = $array[$i];
$d = explode("-",$v->expiration);
if(checkdate(intval($d[1]),1,intval($d[0]))) {
$date =date_create_from_format('Y-m-d',$d[0]."-".$d[1]."-1");
$dateDiff = (array)date_diff($currentDate, $date);
if($dateDiff["days"] < $daysDiff ) {
$daysDiff = $dateDiff["days"];
$nearest = $v;
}
}
}
var_dump($nearest)
?>
Bit more low key (it's been a while since I've done php)

How to add time which is coming from database in laravel

[
{"duration":"00:01:46"},
{"duration":"00:01:23"},
{"duration":"00:01:56"},
{"duration":"00:03:20"},
{"duration":"00:05:41"},
{"duration":"00:02:08"}
]
[
{"duration":"00:01:32"},
{"duration":"00:03:31"},
{"duration":"00:05:56"},
{"duration":"00:03:56"},
{"duration":"00:03:47"},
{"duration":"00:03:38"},
{"duration":"00:02:26"}
]
This is the duration which is coming from my database column duration and now i want to add/sum of these all so i can display it.
Use DateTime, its add method with DateInterval.
<?php
$a = '[
{"duration":"00:01:46"},
{"duration":"00:01:23"},
{"duration":"00:01:56"},
{"duration":"00:03:20"},
{"duration":"00:05:41"},
{"duration":"00:02:08"}
]';
$b = '[
{"duration":"00:01:32"},
{"duration":"00:03:31"},
{"duration":"00:05:56"},
{"duration":"00:03:56"},
{"duration":"00:03:47"},
{"duration":"00:03:38"},
{"duration":"00:02:26"}
]';
$dataA = json_decode($a);
$dataB = json_decode($b);
function sum(array $data): string {
$sum = new DateTime('00:00');
$start = new DateTime('00:00');
foreach ($data as $row) {
$parts = explode(':', $row->duration);
$start->add(new DateInterval(sprintf('PT%sH%sM%sS', $parts[0], $parts[1], $parts[2])));
}
return $start->diff($sum)->format('%H:%I:%S');
}
var_dump(sum($dataA));
var_dump(sum($dataB));
Output:
string(8) "00:16:14"
string(8) "00:24:46"
Note: you would have to display also days if your duration sums to more than 24 hours.

Using PHP to loop JSON and generate a new format of nested JSON

In PHP, how do I loop through the following JSON Object's date key, if the date value are the same then merge the time:
[
{
date: "27-06-2017",
time: "1430"
},
{
date: "27-06-2017",
time: "1500"
},
{
date: "28-06-2017",
time: "0930"
},
{
date: "28-06-2017",
time: "0915"
}
]
Result should looks like this:
[
{
date: "27-06-2017",
time: [{"1430","1500"}]
}, {
date: "28-06-2017",
time: [{"0930, 0915"}]
}
]
Should I create an empty array, then the looping through the JSON and recreate a new JSON? Is there any better way or any solution to reference?
Thank you!
This solution is a little overhead, but if you are sure that your data is sequential and sorted, you can use array_count_values and array_map:
$count = array_count_values(array_column($array, 'date'));
$times = array_column($array, 'time');
$grouped = array_map(function ($date, $count) use (&$times) {
return [
'date' => $date,
'time' => array_splice($times, 0, $count)
];
}, array_keys($count), $count);
Here is working demo.
Another Idea to do this is
<?php
$string = '[{"date": "27-06-2017","time": "1430"},{"date": "27-06-2017","time": "1500"},{"date": "28-06-2017","time": "0930"},{"date": "28-06-2017","time": "0915"}]';
$arrs = json_decode($string);
$main = array();
$temp = array();
foreach($arrs as $arr){
if(in_array($arr->date,$temp)){
$main[$arr->date]['time'][] = $arr->time;
}else{
$main[$arr->date]['date'] = $arr->date;
$main[$arr->date]['time'][] = $arr->time;
$temp[] = $arr->date;
}
}
echo json_encode($main);
?>
live demo : https://eval.in/787695
Please try this:
$a = [] // Your input array
$op= [];//output array
foreach($a as $key => $val){
$key = $val['date'];
$op[$key][] = $val['time'];
}
$op2 = [];
foreach($op as $key => $val){
$op2[] = ['date' => $key, 'time' => $val];
}
// create the "final" array
$final = [];
// loop the JSON (assigned to $l)
foreach($l as $o) {
// assign $final[{date}] = to be a new object if it doesn't already exist
if(empty($final[$o->date])) {
$final[$o->date] = (object) ['date' => $o->date, 'time' => [$o->time]];
}
// ... otherwise, if it does exist, just append this time to the array
else {
$final[$o->date]->time[] = $o->time;
}
}
// to get you back to a zero-indexed array
$final = array_values($final);
The "final" array is created with date based indexes initially so that you can determine whether they've been set or not to allow you to manipulate the correct "time" arrays.
They're just removed at the end by dropping $final into array_values() to get the zero-indexed array you're after.
json_encode($final) will give you want you want as a JSON:
[{"date":"27-06-2017","time":["1430","1500"]},{"date":"28-06-2017","time":["0930","0915"]}]
Yet another solution :
$d = [];
$dizi = array_map(function ($value) use (&$d) {
if (array_key_exists($value->date, $d)) {
array_push($d[$value->date]['time'], $value->time);
} else {
$d[$value->date] = [
'date' => $value->date,
'time' => [$value->time]
];
}
}, $array);
echo json_encode(array_values($d));

Array_sum in php - all values

I wanna sum all values from my array
for example
{
"data": [
{
"message_count": 14051
},
{
"message_count": 12731
},
{
"message_count": 7867
},
{
"message_count": 6053
},
{
"message_count": 4
}
]
}
and that's my code:
<?php
$messages_count = file_get_contents('baza.html');
$json_a=json_decode($messages_count,true);
$counting_base = ($json_a['data']);
echo array_sum($counting_base);
?>
but I still get '0'. Any ideas?
Thank you very much
This is because your array is two-dimensional. array_sum() requires a one-dimensional array. To make it one-dimensional, loop through the array, and use array_sum(), like so:
$new = array();
foreach ($json_a['data'] as $key => $innerArr) {
$new[] = $innerArr['message_count'];
}
echo array_sum($new); // 40706
Online demo
Try this:
array_sum(array_column($json_a['data'], 'message_count'));
Output: 40706
live demo
alternative:
You can do it by a loop:
array_sum()
will not be working since you do not right formated array(1D array).
$sum = 0;
for($i=0; $i<count($counting_base); $i++)
{
$sum += $counting_base['message_count'];
}
echo "Total = ". $sum;

Categories