Search code examples
phparraysmultidimensional-arrayfilter

Find the parent key of the first qualifying row in each subset of a multidimensional array


I want to create function that will return key when value is in one of the array...

First of all, I have multidimensional array:

$stens = array(
    'realistic' => array(
        s1 => array(10),
        s2 => array(11,12),
        s3 => array(13,14,15,16),
        s4 => array(17,18,19,20,21),
        s5 => array(22,23,24,25,26,27,28,29),
        s6 => array(30,31,32,33,34,35,36),
        s7 => array(37,48,39,40,41),
        s8 => array(42,43,44,45,46,47),
        s9 => array(48,49),
        s10 => array(50),
    ),
    'research' => array(
        s1 => array(10,11,12,13,14),
        s2 => array(15),
        s3 => array(16,17,18,19,20),
        s4 => array(21,22,23,24,25,26,27,28),
        s5 => array(29,30,31,32,33),
        s6 => array(34,35,36,37,38),
        s7 => array(39,40,41,42),
        s8 => array(43,44,45,46,47),
        s9 => array(48,49),
        s10 => array(50),
    )
);

My function should return key (from s1 to s10) foreach first array ('realistic', 'research'). For example: my data (raw data) to function is an array:

$raw_data = array
(
   [realistic] => 18
   [research] => 43
)

so function should return array

Array
(
   [realistic] => s4,
   [research] => s8 
)

I tried array_search but i need to search level deeper so it doesn't work.

function sten( $stens, $raw_data )
{
   $sten = array();

    foreach( $raw_data as $type => $value_s )
    {
        foreach( $stens[$type] as $key => $array_values )
            $sten[$type][$key] = array_search( $value_s, $array_values );
    }

    return $sten;
 }

Solution

  • This should work. Use in_array for the arrays on the lowest dimension.

    $sten = array();
    foreach($raw_data as $type => $value_s){
        foreach($stens[$type] as $key => $array_values){
            if(in_array($value_s, $array_values){
                 $sten[$type] = $key;
            }
        }
    }