Home > OS >  Array diff key value php
Array diff key value php

Time:02-04

Can you please tell me how to compare only the date in this array?

<?php
$arr_1 = array();
$arr_2 = array();

array_push($arr_1, array("id" => "1", "date" => "2022-02-03"));
array_push($arr_2, array("id" => "1", "date" => "2022-02-04"));

$result = array_diff($arr_1, $arr_2);

echo json_encode($result);
?>

CodePudding user response:

Convert the arrays to associative arrays, then compare those.

Then you can convert the result back to a 2-dimensional array.

$assoc_1 = array_combine(array_column($arr_1, 'id'), array_column($arr_1, 'date'));
$assoc_2 = array_combine(array_column($arr_2, 'id'), array_column($arr_2, 'date'));
$diff_assoc = array_diff($assoc_1, $assoc_2);
$results = [];
foreach ($diff_assoc as $id => $date) {
    results[] = ['id' => $id, 'date' => $date];
}
  •  Tags:  
  • Related