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";
?>
extracts does not work recursively and will not help in this case. c will not be extracted.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