Associative array in php

Luqman

Why doesn't this work? I am trying to avoid adding an item to array named C that already exists in a Array a

<?php
$a = [["id" => 1, "name" => "Sam"]];
$b = [["id" => 1, "name" => "Sam"],
      ["id" => 2, "name" => "ben"]];
$c = array();

foreach ($b as $x) {

    $id = $x["id"];
    $name = $x["name"];

    foreach ($a as $k) {
        $a_id = $k["id"];

        if ($a_id != $id) {
            $obj = ["id" => $id, "name" => $name];
            array_push($c, $obj);
        }
    }
}
xianglinl
<?php
$a = [
    ['id' => 1, 'name' => 'Sam']
];
$b = [
    ['id' => 1, 'name' => 'Sam'],
    ['id' => 2, 'name' => 'ben']
];
$c = [];

//first set aIds array
$aIds = array_column($a, 'id');
foreach ($b as $x) {
    if (in_array($x['id'], $aIds)) {
        $c[] = $x;
    }

}

var_dump($c);

//array(1) {
//    [0]=>
//  array(2) {
//        ["id"]=>
//    int(1)
//    ["name"]=>
//    string(3) "Sam"
//  }
//}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related