Home > Enterprise >  Remove elements of array when matching data between multiple arrays
Remove elements of array when matching data between multiple arrays

Time:09-28

I have 2 arrays of similar data, they have common property id.

I am wanting to remove entries from the first array if they don't also appear in the second... Is there a simple way to do this?

My arrays look like this:

$billing = [
  ['id' => '1', 'name' => 'one'],
  ['id' => '2', 'name' => 'two'],
  ['id' => '3', 'name' => 'three']
];

$dbdata = [
  ['id' => '1', 'spanish' => 'uno'],
  ['id' => '3', 'spanish' => 'tres']
];

I am currently cycling through them for other data purposes like this:

foreach($billing as &$bill) {
  foreach($dbdata as $db) {
    if ($bill['id'] == $db['id']) {
       // Do some data manipulation here
    }
  }
}

CodePudding user response:

You can note if the row was found, and then store the key of the unfound, to be removed after the first loop is completed

$billing = [
    ['id' => '1', 'name' => 'one'],
    ['id' => '2', 'name' => 'two'],
    ['id' => '3', 'name' => 'three']
];
  
$dbdata = [
    ['id' => '1', 'spanish' => 'uno'],
    ['id' => '3', 'spanish' => 'tres']
 ];

$deleteme = [];
foreach($billing as $idx => &$bill) {
    $found = false;
    foreach($dbdata as $db) {
        if ($bill['id'] == $db['id']) {
            // Do some data manipulation here
            $found = true;
        }
    }
    if (!$found){
        $deleteme[] = $idx;
    }
}
foreach ( $deleteme as $key){
    unset($billing[$key]);
}

print_r($billing);

RESULT

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => one
        )
    [2] => Array
        (
            [id] => 3
            [name] => three
        )
)

CodePudding user response:

array_udiff

$billing = [
    ['id' => '1', 'name' => 'one'],
    ['id' => '2', 'name' => 'two'],
    ['id' => '3', 'name' => 'three']
];

$dbdata = [
    ['id' => '1', 'spanish' => 'uno'],
    ['id' => '3', 'spanish' => 'tres']
];

$filtered = array_udiff($billing, $dbdata, function($a, $b) {
    if ($a['id'] === $b['id']) return 0;
    return ($a['id'] > $b['id']) ? 1 : -1;
});

Which will give you

Array
(
    [1] => Array
        (
            [id] => 2
            [name] => two
        )
)
  • Related