1

I have example array below:

Array
(
    [0] => Array
        (
            [name] => 'item-1'
            [type] => typeA
            [ids] => Array(123, 456, 999)
        )

    [1] => Array
        (
            [name] => 'item-2'
            [type] => typeA
            [ids] => Array(555, 4444, 666)
        )

    [2] => Array
        (
            [name] => 'item-3'
            [type] => typeB
            [ids] => null
        )
    [3] => Array
        (
            [name] => 'item-4'
            [type] => typeB
            [ids] => Array(555)
        )
 )

As an example, I want to search the array for all entries where type is typeA or id = 555. I just need to retrieve the name fields (or at least the keys and from there the names). In the hypothetical example, the search would result in item-1, item-2 and item-4

I tried a few different PHP functions. For example

$keys = array_keys(array_column($parent_array, 'type'), 'typeA');

The above works for retrieving keys when search is based on the [type] field. But doesn't work for [ids].

Any suggestions?

hani416
  • 11
  • 1

1 Answers1

1

I'm going to suggest using the function array_filter to perform your searching

The main element of this is the call back function with the type or id logic

function search_my_array( $array, $type, $id )
{
  return array_filter( $array, function( $item ) use ( $type, $id ){
    return $item['type'] === $type or ( is_array( $item['ids'] ) and in_array( $id, $item['ids'] ) );
  });
}

$array = array(
  array('name'=>'item-1','type'=>'typeA','ids'=>array(123,456,789)),
  array('name'=>'item-2','type'=>'typeA','ids'=>array(555,444,666)),
  array('name'=>'item-3','type'=>'typeB','ids'=>null),
  array('name'=>'item-4','type'=>'typeB','ids'=>array(555)),
);

$result = search_my_array( $array, 'typeA', 555 );

The result is the exact same array structure, just only with the three items you want, and then you can perform your array_column call

array_column( $result, 'name' );

Also if you don't always have the type or ids field, strengthen the validation with isset

return ( isset( $item['type'] ) and $item['type'] === $type ) or ( isset( $item['ids'] ) and is_array( $item['ids'] ) and in_array( $id, $item['ids'] ) );
Scuzzy
  • 12,186
  • 1
  • 46
  • 46
  • 1
    Thank you! This worked beautifully! I am not sure why the question was closed, I don't believe the other referenced question has the exact solution I was looking for. But your answer is the correct one for my problem. Thanks again. – hani416 Mar 17 '21 at 00:07
  • Agreed, the other question returns a single key and not multiple matches – Scuzzy Mar 18 '21 at 03:24