I do a foreach on an object that I call $file
. This object has a property which is the datetime ($file[6]) and another with the name ($file[0]). I need to add the object to an array if the difference between createDate
and $file[6]
are within 10 minutes of each other.
My desired result structure is:
[
[ $file[0], $file[6] ], // More than 1 results
[ $file[0], $file[6] ],
...
]
As you can see in the code below:
$createDate = $prop['created_date'];
$result = array();
foreach($obj['files'] as $file) {
$fileName = $file[0];
$fileDateTime = $file[6];
$differenceInSeconds = strtotime($fileDateTime) - strtotime($createDate);
$differenceInSeconds = abs($differenceInSeconds);
$convertMinutes = 10 * 60; // 10 minutes
if ($differenceInSeconds < $convertMinutes) {
// Need a array of array that show the name ($file[0]) and datetime ($file[6])
// when the difference between $createDate and $file[6] is less 10 minutes
// (or is between 0 and 600, I guess)
array_push($result, $file); // Here need push array name and date
break;
}
}
echo json_encode($result);
Var_dump in $createDate and $file show this:
$createDate:
DataType: json Message: object(IP_DateTime)#77 (3) {
["date"]=>
string(26) "2022-04-25 03:38:15.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(17) "America/Sao_Paulo"
}
$file:
array(9) {
[0]=>
string(26) "20220407_10_22_30_L100.SVL"
[1]=>
int(2)
[2]=>
string(8) "20220407"
[3]=>
int(4766)
[4]=>
int(307)
[5]=>
int(101366)
[6]=>
string(19) "2022-04-07 13:34:10"
[7]=>
int(0)
[8]=>
int(1)
}
This should work if I understood correctly
$createDate = $prop['created_date'];
$result = array();
$index = 0;
foreach ($obj['files'] as $file) {
$fileName = $file[0];
$fileDateTime = $file[6];
$differenceInSeconds = strtotime($fileDateTime) - strtotime($createDate);
$differenceInSeconds = abs($differenceInSeconds);
$convertMinutes = 600; // 10 minutes
if ($differenceInSeconds < $convertMinutes) {
$result[$index] = array($fileName,$fileDateTime);
$index++;
}
}
echo json_encode($result);
Adding a bit of explanation: I'm using $result[$index] instead of array_push because if you push an array into an array, it would just push in all its items instead of adding the new array as an actual array, which was happening to you.