Search code examples
phpmultidimensional-arrayfilteringimplodearray-column

How to convert array values to comma seperated string based on specified given array values..?


I have the array as specified below

Array
(
  [5] => Array
  (
    [id] => 5
    [first_name] => Diyaa
    [profile_pic] => profile/user5.png
  )

  [8] => Array
  (
    [id] => 8
    [first_name] => Raj
    [profile_pic] => profile/user8.png
  )

  [12] => Array
  (
    [id] => 12
    [first_name] => Vanathi
    [profile_pic] => profile/user12.png
  )

  [15] => Array
  (
    [id] => 15
    [first_name] => Giri
    [profile_pic] => profile/user15.png
  )

  [19] => Array
  (
    [id] => 19
    [first_name] => Mahesh
    [profile_pic] => profile/user19.png
  )
)

I have another array as given below

Array
(
  [0] => 8
  [1] => 15
  [2] => 19
)

I want the first_name from the first array, based on second array values => 8, 15 and 19.
So I need Raj,Giri,Mahesh as output as comma separated string.
How to get this..?


Solution

  • This code will work for you :-

    $array1 = array_column($array, 'first_name','id');
    $array2 = [8,15,19];
    $names = array_intersect_key($array1, array_flip($array2));
    $names = implode(',',$names);
    echo $names;