1

I need walking trought json mixed arrays and objects.

I try, but get a [ErrorException] Array to string conversion

$epoJson = json_decode($json, true);
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($epoJson), RecursiveIteratorIterator::CATCH_GET_CHILD) as $key => $value) {
   echo 'My node ' . $key . ' with value ' . $value . PHP_EOL;
}

NOTE: I don't need a echo, var_dump or other , of course... I need iterate for put other code for work with values... code echo it's only for visualize problem... if I used echoot's for simple question: if $value, it's not string...

Try search some examples or libraries for walk on json mixed but not get anything.

http://sandbox.onlinephpfunctions.com/code/4bd4fbc5e43ed439add7d4ba497b830d498ce4ac

2 Answers 2

1

Try to use this code 100% working:

Note: $value is array not string

<?php

$epoJson = json_decode($epoJson, true);
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($epoJson), RecursiveIteratorIterator::CATCH_GET_CHILD) as $key => $value) {
   //echo 'My node ' . $key . ' with value ' . $value . PHP_EOL;
    echo $key.'<br />';
    echo "<pre>"; print_r($value); // $value is array not string
    echo '<hr />';
}

?>
Sign up to request clarification or add additional context in comments.

1 Comment

I don't need a var_dump or print $value. I ask for iterate on complex json with arrays and objects mixed.
1

After looking for a good time, I realized that something was wrong, because I tried to validate when it was an object.

Remember that Laravel has a helper that does more or less what I want, at least depth

It traverses a multidimensional array with or without objects and converts it into a one-dimensional array.

Just what I needed.

/**
     * Flatten a multi-dimensional associative array with dots.
     *
     * @param  array   $array
     * @param  string  $prepend
     * @return array
     */
    public static function dot($array, $prepend = '')
    {
        $results = [];

        foreach ($array as $key => $value) {
            if (is_array($value) && ! empty($value)) {
                $results = array_merge($results, static::dot($value, $prepend.$key.'.'));
            } else {
                $results[$prepend.$key] = $value;
            }
        }

        return $results;
    }

http://sandbox.onlinephpfunctions.com/code/c9d8b0c293901325829219f5c03d655748802109

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.