简体   繁体   中英

PHP multi dimensional Array

Array
(
    [a] => Array
        (
            [a] => Array
                (
                    [a] => a
                    [b] => b
                )

            [b] => Array
                (
                    [a] => a
                    [b] => b
                )

        )

    [b] => Array
        (
            [a] => Array
                (
                    [a] => a
                    [b] => b
                )

            [b] => Array
                (
                    [a] => a
                    [b] => b
                )

        )

)

how to get a string below from array above?

aaa,aab,aba,abb,baa,bab,bba,bbb

You could simply write a recursive function to automatically concatenate the keys together.

function getKeysString($array, $prefix = '') {  
  $keys = array();

  foreach($array as $key => $value) {
    $str = $prefix.$key;

    if(is_array($value)) {
      $str = getKeysString($value, $str);
    }

    $keys[] = $str;
  }

  return implode(',', $keys);
}

So, given the array:

$arr = array (
  'a' => array (
    'a' => array (
      'a' => null,
      'b' => null
    ),
    'b' => array (
      'a' => null,
      'b' => null
    )
  ),
  'b' => array (
    'a' => array (
      'a' => null,
      'b' => null
    ),
    'b' => array (
      'a' => null,
      'b' => null
    )
  )
);

The following would give you the result you want:

$result = getKeysString($arr);
 $str = array();
foreach($array as $key1 => $value1)
{
   foreach($value1 as $key2 => $value2)
   {
     foreach($value2 as $key3 => $value3)
        $str[]= $key1.$key2.$key3;
   }
}

echo implode(',', $str);

Multidimensional array in PHP

$Student = array(array("Adam",10,10),

                array("Ricky",10,11),

                array("Bret",15,14),

                array("Ram",14,17)
          );

for($i=0;$i<=3;$i++){

    for($j=0;$j<=2;$j++){
        print_r($Student[$i][$j]);

        echo "<br>";    
    }
}
<?php    
     $Student = array(array("Adam",10,10,10),    
                      array("Ricky",10,11,10),    
                      array("Bret",15,14,10),    
                      array("Ram",14,17,10)
                     );

    for($i=0;$i<=3;$i++){    
        for($j=0;$j<=3;$j++){    
                print_r($Student[$i][$j]);    
                echo "<br>";            
        }
    }
?>

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