Home > Net >  Result to be an array of array in PHP
Result to be an array of array in PHP

Time:08-28

better explaining my question. 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 add the object in an array if the diff between createDate and $file[6] are 10 minutes. And the results I return in an array with the follow structure:

[
  [ $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)
}

CodePudding user response:

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);
  • Related