PHP - Traversing object fails if element's value is not of type string
P粉769045426
P粉769045426 2023-07-30 18:07:04
0
1
412

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:

{ "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" }] }

It is converted to an array like this (for a specific reason):

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" ] ] ]

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:

foreach ($arrTree as $k => $v) { if (is_string($v)) { //Do something here } }

I'm sure I'm missing something basic here, but I'm tired of looking for problems. Thanks.

P粉769045426
P粉769045426

reply all (1)
P粉615886660

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 } } } } } }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!