0

I have a question. So I have this array :

$a_list_id = array(
   0 => 1234
   1 => 739
   3 => 538
);

And this array :

$a_users = array(
    0 => array(
        id => 15627,
        name => test
    ),
    1 => array(
        id => 1234,
        name => test1
    ),
    2 => array(
        id => 739,
        name => test2
    )
)

The result should be :

$a_response = array(
    0 => array(
       id => 1234,
       name => test1 
    )
)

Because the id 1234 is in both arrays. I try with array_intersect but not work. Can you help me please ?

user7424312
  • 137
  • 3
  • 10

4 Answers4

1

Just use loops :

$a_response = array();
foreach ($a_users as $array) {
    if (in_array($array['id'], $a_list_id)) {
        $a_response []= $a_users;
    }
}
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84
1

array_intersect will only produce useful results if the values of both arrays can be cast to the same type. You've got an array of integers and another array of arrays, they can never* match so intersect will always be empty

If you want an intersection between the arrays then you have two options:

  • Index the arrays so their keys are the values you want to intersect and use array_intersect_key
  • Implement your own array comparison logic with array_uintersect and a callback function that knows the structure of the arrays being compared

example of the former:

$a_list_id = array(
   1234 => 1234
   739 => 739
   538 => 538
);

$a_users = array(
    15627 => array(
        id => 15627,
        name => test
    ),
    1234 => array(
        id => 1234,
        name => test1
    ),
    739 => array(
        id => 739,
        name => test2
    )
)

var_dump (array_intersect_key ($a_users, $a_list_id));

Example of the latter:

var_dump (array_uintersect ($a_users, $a_list_id, function ($user, $id) {
    return $user ["id"] - $id; // Result should be 0 if they match, as per documentation
}))

*They can be considered the same in the case where one value is integer 0 and the other is an empty array, but that's not very useful

GordonM
  • 31,179
  • 15
  • 87
  • 129
0

Have you tried using array_intersect_uassoc? http://php.net/manual/en/function.array-intersect-uassoc.php

function compare_ids($a, $b)
{
    return $a - $b['id'];
}

print_r(array_intersect_uassoc($a_list_id, $a_users, "compare_ids"));
kjames
  • 646
  • 1
  • 7
  • 20
0

Try the below code using array_search() function:

$a_list_id = array(1234, 538,739);

$a_users = array(
 array(
    'id'=> 15627,
    'name' => 'test'
),
 array(
    'id' => 1234,
    'name' => 'test1'
),
 array(
    'id' => 739,
    'name' => 'test2'
)
);

foreach($a_users as $a_user){
  if (in_array($a_user['id'], $a_list_id)) {
     $a_response[array_search($a_user['id'], $a_list_id)] = $a_user;
  }
}

print_r($a_response);
mith
  • 1,680
  • 1
  • 10
  • 12