Filtering a multidimensional array using a key in PHP

I have a question about filtering a multidimensional array in PHP. What I would like to achieve is to pull a specific array of items (mediacontent value) from an existing array. This is what I got so far:

Existing multidimensional array:

$multidimensional_array = array(
    'entry' => array(
        0 => array(
            'width' => array(
                '$t' => '1536'
            ),
            'height' => array(
                '$t' => '2048'
            ),
            'id' => array(
                '$t' => '878974'
            ),
            'mediagroup' => array(
                'mediacontent' => array(
                    'url' => 'http://website/urltotheobject.png',
                    'width' => 384,
                    'medium' => 'image',
                    'type' => 'image/jpeg',
                    'height' => 512
                )
            )
        ),
        1 => array(
            'width' => array(
                    '$t' => '5486'
            ),
            'height' => array(
                    '$t' => '1144'
            ),
            'id' => array(
                '$t' => '485435'
            ),
            'mediagroup' => array(
                'mediacontent' => array(
                    'url' => 'http://website/urltotheobject.png',
                    'width' => 512,
                    'medium' => 'image',
                    'type' => 'image/jpeg',
                    'height' => 384
                )
            )   
        )
    )
);

      

Function A (not working correctly) to filter an array

function filterResponseByKey($keyToFilter,$array){

    foreach ($array as $key => $value) 
    {
        if($key == $keyToFilter)
        {
            return $value;
        }
        elseif(is_array($value))
        {
            $result = filterResponseByKey($keyToFilter, $value);

            if($result != false)
            {
                return $result;             
            }
        }
    }
    return false;
}

      

I'm new to PHP and I hope you guys can point me in the right direction and tell me what I'm doing wrong here.

I have researched the following (alternative) websites, but I could not find an answer that suits my needs.

understanding recursion , PHP filter_array

+3


source to share


4 answers


In your particular case, I would recommend that you have an array of objects, since elements 0 and 1 are similar and mediacontent is like an internal variable.

If you really want to do this, you can only get the mediacontent array with a map

 array_map($multidimensional_array['entry'],function($obj){
     return $obj['mediagroup']['mediacontent'];
 });

      

If you want something more dynamic and recursive



 function recursive_filter_by_key($keyname,$list){
    $result=[];
    foreach($list as $key=>$obj){
         if($key==$keyname) 
            array_push($result,$obj);

         else if(gettype($obj)=='array')//not necesary to check if its equal to the $key as this wouldn't run if it was
                 $result = array_merge($result,recursive_filter_by_key($obj));
    }
    return $result;

 }

      

This function can return complete arrays within the result array as long as they are the value of the key you are looking for

I would like you to comment, although I think I do not really understand your question.

Also there is another similar post on the site if you haven't crossed it How to recursively run array_filter on a PHP array?

+1


source


The most practical solution for this is using iterators :

$iter = new RecursiveIteratorIterator(
                new RecursiveArrayIterator($multidimensional_array),
                RecursiveIteratorIterator::SELF_FIRST
);
foreach($iter as $key => $value) {
  if(ctype_alpha($key) && $key == 'mediacontent') {
    echo "Media Content: ".print_r($value, true)."\n";
  }
}

      

This will output:



Media Content: Array
(
    [url] => http://website/urltotheobject.png
    [width] => 384
    [medium] => image
    [type] => image/jpeg
    [height] => 512
)

Media Content: Array
(
    [url] => http://website/urltotheobject.png
    [width] => 512
    [medium] => image
    [type] => image/jpeg
    [height] => 384
)

      

Iterators are a very underrated PHP feature, although sometimes they have complex syntax, in which case you are interested in nodes instead of leaves that require an additional mode parameter. However, recursive iterators simplify a lot of recursive operations.

+1


source


You can try this route also for just media coverage ....

$multidimensional_array = array(
        'entry' => array(
            0 => array(
                'width' => array(
                    '$t' => '1536'
                ),
                'height' => array(
                    '$t' => '2048'
                ),
                'id' => array(
                    '$t' => '878974'
                ),
                'mediagroup' => array(
                    'mediacontent' => array(
                        'url' => 'http://website/urltotheobject.png',
                        'width' => 384,
                        'medium' => 'image',
                        'type' => 'image/jpeg',
                        'height' => 512
                    )
                )
            ),
            1 => array(
                'width' => array(
                    '$t' => '5486'
                ),
                'height' => array(
                    '$t' => '1144'
                ),
                'id' => array(
                    '$t' => '485435'
                ),
                'mediagroup' => array(
                    'mediacontent' => array(
                        'url' => 'http://website/urltotheobject.png',
                        'width' => 512,
                        'medium' => 'image',
                        'type' => 'image/jpeg',
                        'height' => 384
                    )
                )
            )
        )
    );

    function getMediaContent($item){
        return $item['mediagroup']['mediacontent'];
    }
    $mediacontent = array_map('getMediaContent', $multidimensional_array['entry']);
    print '<pre>';
    print_r($mediacontent);

      

0


source


function filterResponseByKey($keyToFilter,$array){

    foreach ($array as $key => $value) 
    {
        if($key === $keyToFilter)
        {
            return $value;
        }
        elseif(is_array($value))
        {
            $result = filterResponseByKey($keyToFilter, $value);

            if($result != false)
            {
                return $result;             
            }
        }
    }
    return false;
}

      

Now we are working!

edit: explain:

Using "==" checks if it is equal regardless of the type, so when it encounters a gap, it will use both values ​​to check, since interger int ('anystring') results in 0, so key 0 = string 'Media content '

0


source







All Articles