7

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?

3
  • 2
    php.net/manual/en/function.array-walk-recursive.php - it will not cover all cases (more complicaed structures?)...but, should help - basically, you need recursion -> check if value is array, call function again, etc, etc... stackoverflow.com/questions/6088687/… Commented Dec 24, 2016 at 13:06
  • @sinisake Is it possible to retrieve the full var-"path"/parent key, for example when my code is $fruits = ['sweet' => ["hi" => "nett"], 'sour' => 'lemon']; function test_print($item, $key) { echo "$key holds $item\n"; } array_walk_recursive($fruits, 'test_print'); That I get as additional path which key is meant? $fruits["sweet"]["hi"] Commented Dec 24, 2016 at 13:31
  • Yesterday someone had similar problem: stackoverflow.com/questions/41284689/… please check latest answer, it should help. Commented Dec 24, 2016 at 13:53

3 Answers 3

3

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
}
Sign up to request clarification or add additional context in comments.

Comments

3

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 );
        }
    }
}

Comments

1

You can create a recursive function to treat it.

function sweep_array(array $array)
{
    foreach($array as $key => $value){

        if(is_array($value))
        {
            sweep_array($value);
        } 
        else 
        {
            echo $key . " => " . $value . "<br>";
        }   
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.