Home  >  Q&A  >  body text

PHP - Traversing object fails if element's value is not of type string

<p>I have a simple question, but no matter what, I can't figure out what's going on. I have a JSON string that looks like this: </p> <pre class="brush:php;toolbar:false;">{ "network_title": "Network", "class_title": "Class", "grades": [{ "number": "Pre-K", "label": "Pre-Kindergarten", "order": 1, "id": "34567" }, { "number": "TK", "label": "Transitional Kindergarten", "order": 2, "id": "23456" }, { "number": "K", "label": "Kindergarten", "order": 3, "id": "12345" }] }</pre> <p>It is converted to an array like this (for a specific reason): </p> <pre class="brush:php;toolbar:false;">array:3 [ "network_title" => "Network" "class_title" => "Class" "grades" => array:3 [ 0 => array:4 [ "number" => "Pre-K" "label" => "Pre-Kindergarten" "order" => 1 "gid" => "aa71da69-93ab-11e9-bda9-06f442b19d06" ] 1 => array:4 [ "number" => "TK" "label" => "Transitional Kindergarten" "order" => 2 "gid" => "d3c6754a-6298-48d0-9afa-6a19bafb8464" ] 2 => array:4 [ "number" => "K" "label" => "Kindergarten" "order" => 3 "gid" => "a815a771-9aff-4020-b7d2-0c95a05da21e" ] ] ]</pre> <p>Then I try to iterate through the array, and when it finds an element whose type is not string (like the order element), it gets an Invalid argument supplied for foreach() error. The error message says that the foreach() line is problematic. Here is a code example: </p> <pre class="brush:php;toolbar:false;">foreach ($arrTree as $k => $v) { if (is_string($v)) { //Do something here } }</pre> <p>I'm sure I'm missing something basic here, but I'm tired of looking for problems. Thanks. </p>
P粉769045426P粉769045426417 days ago461

reply all(1)I'll reply

  • P粉615886660

    P粉6158866602023-07-31 15:41:35

    The problem is that $arrTree is a multidimensional array.

    The foreach loop in your code only traverses the first level of the array, but does not traverse nested arrays (such as "grades"). When it encounters "grades" the value of $v is not a string but an array, that's why the is_string($v) check fails.

    You need to add a nested foreach loop to handle this structure.

    Here is an example showing how to achieve this:

    foreach ($arrTree as $k => $v)
    { 
        if (is_string($v)) 
        {
            //Do something here
        }
        else if (is_array($v))
        {
            foreach($v as $key => $value)
            {
                if(is_string($value))
                {
                    //Do something here
                }
                else if(is_array($value))
                {
                    foreach($value as $innerKey => $innerValue)
                    {
                        if(is_string($innerValue))
                        {
                            //Do something here
                        }
                    }
                }
            }
        }
    } 

    reply
    0
  • Cancelreply