Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get every key-value-pair from PHP-array

I need to get every key-value-pair from an array in PHP. The structure is different and not plannable, for example it is possible that a key contains an additional array and so on (multidimensional array?). The function I would like to call has the task to replace a specific string from the value. The problem is that the function foreach, each, ... only use the main keys and values.

Is there existing a function that has the foreach-function with every key/value?

like image 346
HelloToYou Avatar asked Dec 24 '16 13:12

HelloToYou


2 Answers

There is not a built in function that works as you expect but you can adapt it using the RecursiveIteratorIterator, walking recursively the multidimensional array, and with the flag RecursiveIteratorIterator::SELF_FIRST, you would get all the elements of the same level first, before going deeper, not missing any pair.

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST);

foreach ($iterator as $key => $item) {
    // LOGIC
}
like image 115
Dez Avatar answered Oct 17 '22 10:10

Dez


The usual approach to this kind of task is using a recursive funcion.

Let's go step by step:

First you need the foreach control statement...

http://php.net/manual/en/control-structures.foreach.php

..that let you parse the associative array without knowing keys' names beforehand.

Then is_array and is_string (and eventually is_object, is_integer...) let you check the type of each value so you can act properly.

http://php.net/manual/en/function.is-array.php

http://php.net/manual/en/function.is-string.php

If you find the string to be operated then you do the replace task

If you find an array the function recalls itself passing the array just parsed.

This way the original array will be parsed down to the deepest level without missing and key-value pair.


Example:

function findAndReplaceStringInArray( $theArray )
{
    foreach ( $theArray as $key => $value)
    {
        if( is_string( $theArray[ $key ] )
        {
            // the value is a string
            // do your job...

            // Example:
            // Replace 'John' with 'Mike' if the `key` is 'name'

            if( $key == 'name' && $theArray[ $key ] == "John" )
            {
                $theArray[ $key ] = "Mike";
            }
        }
        else if( is_array( $theArray[ $key ] )
        {
            // treat the value as a nested array

            $nestedArray = $theArray[ $key ];

            findAndReplaceStringInArray( $nestedArray );
        }
    }
}
like image 39
Paolo Avatar answered Oct 17 '22 12:10

Paolo