Iterating over a complex Associative Array in PHP

后端 未结 7 1874
广开言路
广开言路 2020-11-27 17:00

Is there an easy way to iterate over an associative array of this structure in PHP:

The array $searches has a numbered index, with between 4 and 5 assoc

相关标签:
7条回答
  • 2020-11-27 17:41

    Looks like a good place for a recursive function, esp. if you'll have more than two levels of depth.

    function doSomething(&$complex_array)
    {
        foreach ($complex_array as $n => $v)
        {
            if (is_array($v))
                doSomething($v);
            else
                do whatever you want to do with a single node
        }
    }
    
    0 讨论(0)
  • 2020-11-27 17:45

    Nest two foreach loops:

    foreach ($array as $i => $values) {
        print "$i {\n";
        foreach ($values as $key => $value) {
            print "    $key => $value\n";
        }
        print "}\n";
    }
    
    0 讨论(0)
  • 2020-11-27 17:47

    Can you just loop over all of the "part[n]" items and use isset to see if they actually exist or not?

    0 讨论(0)
  • 2020-11-27 17:54

    I'm really not sure what you mean here - surely a pair of foreach loops does what you need?

    foreach($array as $id => $assoc)
    {
        foreach($assoc as $part => $data)
        {
            // code
        }
    }
    

    Or do you need something recursive? I'd be able to help more with example data and a context in how you want the data returned.

    0 讨论(0)
  • 2020-11-27 17:59

    I know it's question necromancy, but iterating over Multidimensional arrays is easy with Spl Iterators

    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
    
    foreach($iterator as $key=>$value) {
        echo $key.' -- '.$value.'<br />';
    }
    

    See

    • http://php.net/manual/en/spl.iterators.php
    0 讨论(0)
  • 2020-11-27 18:00

    You should be able to use a nested foreach statment

    from the php manual

    /* foreach example 4: multi-dimensional arrays */
    $a = array();
    $a[0][0] = "a";
    $a[0][1] = "b";
    $a[1][0] = "y";
    $a[1][1] = "z";
    
    foreach ($a as $v1) {
        foreach ($v1 as $v2) {
            echo "$v2\n";
        }
    }
    
    0 讨论(0)
提交回复
热议问题