简体   繁体   中英

Loop through array that might be multi dimensional

I might have the following array()

Array([
    0
]=>Array([
    part_id
]=>6[
    part_user_id
]=>2[
    part_department
]=>3[
    part_category
]=>1[
    part_subcategory
]=>1[
    part_name
]=>SparePart[
    part_qty
]=>1[
    part_condition
]=>New[
    part_description
]=>Thisisadescription[
    part_image
]=>images/parts/default.jpg)[
    1
]=>Array([
    part_id
]=>7[
    part_user_id
]=>2[
    part_department
]=>3[
    part_category
]=>1[
    part_subcategory
]=>1[
    part_name
]=>SparePart[
    part_qty
]=>1[
    part_condition
]=>New[
    part_description
]=>Thisisadescription[
    part_image
]=>images/parts/default.jpg))

From data I have got from MYSQL, the same query might also return more than one row so I could also receive this array()

Array([
    part_id
]=>7[
    part_user_id
]=>2[
    part_department
]=>3[
    part_category
]=>1[
    part_subcategory
]=>1[
    part_name
]=>SparePart[
    part_qty
]=>1[
    part_condition
]=>New[
    part_description
]=>Thisisadescription[
    part_image
]=>images/parts/default.jpg)

I am looping through to output in my HTML

foreach($myResults as $row => $value){

}

This loop will work fine when I receive more than 1 row from the DB. If I receive 1 row I obviously run into problem.

What is the best way for me to check what I have received in order to loop or simply output dependent on my result?

Check if value is an array. If yes loop it too.

if (is_array($value)) foreach ($value as $value2) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM