当前位置: 动力学知识库 > 问答 > 编程问答 >

How can I get variable from multi dimensional array with php?

问题描述:

Screenshot of my array like this;

Array(

[a] => val1

[b] =>

Array(

[c]=>68

)

)

How can I get variable as;

a=val1

c=68

with php using loop?

网友答案:
$array = array('a' => 'val1', 'b' => array('c' => 68));
echo $array['a']; //val1
echo $array['b']['c']; //68

To just output all values of a multidimensional array:

function outputValue($array){
  foreach($array as $key => $value){
    if(is_array($value)){
      outputValue($value);
      continue;
    }
    echo "$key=$value" . PHP_EOL;
  }
}

The same can be accomplished using array_walk_recursive():

array_walk_recursive($array, function($value, $key){echo "$key=$value" . PHP_EOL;});
网友答案:

Have a look at: http://us.php.net/manual/en/function.http-build-query.php

It will take an array (associative) and convert it to query string.

网友答案:

You use the PHP function extract() http://php.net/manual/en/function.extract.php

Like this:

<?php

$var_array = array("color" => "blue",
               "size"  => "medium",
               "shape" => "sphere");
extract($var_array);

echo "$color, $size, $shape\n";

?>
网友答案:

You would use:

foreach ($x as $k=>$v) 

Where $x is your array; this will loop through each element of $x and assign $k the key and $v the value.

As an example, here's a code snippet that sets the array and displays it:

$x = array('a'=>'val1', 'b'=>'val2');
foreach ($x as $k=>$v) {
    echo "$k => $v<br />";
}
网友答案:

If you know its maximum one array deep you could use

foreach ($myArray as $key=>$val) {
  if (is_array($val) {
    foreach ($val as $key2=>$val2) {
      print $key2.'='.$val2;
    }
  } else {
    print $key.'='.$val;
  }
}

if it could be more, use a function

function printArray($ar) {
  foreach ($myArray as $key=>$val) {
    if (is_array($val) {
      printArray($val)
    } else {
      print $key.'='.$val;
    }
  }
}

printArray($myArray);
网友答案:

If you are trying to extract the variables try:

<?php
$array = array('a' => 'val1', 'b' => array('c' => 68));

$stack = array($array);
while (count($stack) !== 0) {
    foreach ($stack as $k0 => $v0) {
        foreach ($v0 as $k1 => $v1) {
            if (is_array($v1)) {
                $stack[] = $v1;
            } else {
                $$k1 = $v1;
            }
            unset($k1, $v1);
        }
        unset($stack[$k0], $k0, $v0);
    }
}
unset($stack);

This will create $a (val1) and $c (68) inside of the current variable scope.

网友答案:

You can use RecursiveIteratorIterator + RecursiveArrayIterator on ArrayIterator

Example Your Current Data

$data = array(
  'a' => 'val1',
  'b' => array('c'=>68)
);

Solution

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator(new ArrayIterator($data)));
echo "<pre>";
foreach ($it as $k=> $var)
{
    printf("%s=%s\n",$k,$var);
}

Output

a=val1
c=68

See Live Demo PHP 5.1.0 - 5.4.9

分享给朋友:
您可能感兴趣的文章:
随机阅读: