简体   繁体   中英

loop through 3-dimensional array php

I am trying to loop through a multidimensional array and keep banging my head against the wall trying to figure it out. I am essentially trying to print all values of ID.

This is what I have so far, but it keeps giving me an "array to string conversion" error.

foreach ($threadsarray as $key => $threads) {   
    foreach ($threads as $anotherkey => $i) {
        foreach($i as $id => $threadid)
        echo 'key:'.$key[0]. ' AnotherKey: '.$anotherkey["threads"].' AnotherAnotherKey: '.$i["id"].' value:'.$threadid.'<br>';
    }
}

I'm trying to mimic what this would do, but using a "For Loop"

$threadsarray['threads']['0']['id'];
$threadsarray['threads']['1']['id'];

And here is the array.....

Array
(
    [threads] => Array
        (
            [0] => Array
                (
                    [archived] => 
                    [attachment] => 
                    [business_purpose] => booking_direct_thread
                    [id] => 178369845
                    [inquiry_reservation] => 
                    [last_message_at] => 2017-04-07T18:52:07Z
                    [listing] => Array
                        (

This is the way it can be done

foreach ($threadsarray['threads'] as $thread) {   
     print $thread['id'];
}

for version

$idx = count($threadsarray['threads']);
for($i=0;$i<$idx;$i++){
   print $threadsarray['threads'][$i]['id'];
}

The error you are getting is because you are trying to echo out an Array.

I would do this:

foreach($threadsarray['threads'] as $key => $thread){
    echo 'key:' . $key . ' - ';
    foreach($thread as $key2 => $value2){
        echo 'key2:' . $key2 . ' - ';
        if(is_array($value2)){
            foreach($value2 as $key3 => $value3){
                echo 'key3:' . $key3 . ' - value3: ' . $value3;
            }
        }else{
            echo 'value: ' . $value2;
        }
    }
}

you can always inspect the whole array structure doing print_r($threadsarray)

Better use a recursive function for any amount of 'levels':

function printAll($a) {
    if (!is_array($a)) {
        echo $a, ' ';
        return;
    }

    foreach($a as $k => $value) {

         printAll($k);
         printAll($value);

    }
}

You can call it like: printAll($threadsarray);

Reference

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