How to get each key-value pair from a PHP array

I need to get every key-value pair from an array in PHP. The structure is different and not planned, for example, it is possible that the key contains an additional array, etc. (Multidimensional array?). The function I would like to call has the task of replacing a specific string from a value. The problem is that in function foreach, each... used only the basic keys and values.

Is there a function that has a foreach-function with each key / value?

+4
source share
3 answers

The usual approach to this problem is to use a recursive function .

Release step by step:

First you need a control instruction foreach...

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

.. which allow you to parse an associative array without knowing the key names in advance.

Then is_arrayand is_string(and, finally is_object, is_integer...), you can check the type of each value, so you can act correctly.

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 used, then you are doing the replacement task

If you find an array, the function calls the transmitting array itself, which is simply parsed.

, -.


:

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

, , , , RecursiveIteratorIterator, RecursiveIteratorIterator::SELF_FIRST, , , .

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

foreach ($iterator as $key => $item) {
    // LOGIC
}
+1

You can create a recursive function to handle it.

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

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

Source: https://habr.com/ru/post/1664764/


All Articles