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
Related
So I have the following array:
$array = array(array('fruit1' => 'apple'),
array('fruit2' => 'orange'),
array('veg1' => 'tomato'),
array('veg2' => 'carrot'));
and I want to run a function like this:
array_remove_recursive($array, 'tomato');
so the output is this:
$array = array(array('fruit1' => 'apple'),
array('fruit2' => 'orange'),
array('veg2' => 'carrot')); // note: the entire array containing tomato has been removed!
Is this solvable?
This will recursively unset the matching variable at any depth and then remove the parent element only if it is empty.
function recursive_unset(array &$array, $unwanted_val) {
foreach ($array as $key => &$value) {
if (is_array($value)) {
recursive_unset($value, $unwanted_val);
if(!count($value)){
unset($array[$key]);
}
} else if($value == $unwanted_val){
unset($array[$key]);
}
}
}
Function to remove recursively many values from multidimensional array.
# Example 1
$arr1 = array_remove_recursive($arr, 'tomato');
# Example 2
$arr2 = array_remove_recursive($arr, ['tomato', 'apple']);
function array_remove_recursive($arr, $values)
{
if (!is_array($values))
$values = [$values];
foreach ($arr as $k => $v) {
if (is_array($v)) {
if ($arr2 = array_remove_recursive($v, $values))
$arr[$k] = $arr2;
else
unset($arr[$k]);
} elseif (in_array($v, $values, true))
unset($arr[$k]);
}
return $arr;
}
function array_remove_recursive($getArray,$getAssocValue)
{
$returnArray = array();
if(is_array($getArray))
{
foreach($getArray as $indAssocValue)
{
if(is_array($indAssocValue))
{
foreach($indAssocValue as $innerKey=>$innerVal)
{
if($innerVal!=$getAssocValue and $innerKey!="")
{
$returnArray[] = array("$innerKey"=>$innerVal);
}
}
}
}
}
return $returnArray;
}
$array = array(array('fruit1' => 'apple'),
array('fruit2' => 'orange'),
array('veg1' => 'tomato'),
array('veg2' => 'carrot'));
print_r($array);
echo "<br />";
$array = array_remove_recursive($array, 'tomato');
print_r($array);
hope the above code would be helpfull.
Suppose I have an array like this:
$array = array("a","b","c","d","a","a");
and I want to get all the keys that have the value "a".
I know I can get them using a while loop:
while ($a = current($array)) {
if ($a == 'a') {
echo key($array).',';
}
next($array);
}
How can I get them using a foreach loop instead?
I've tried:
foreach ($array as $a) {
if ($a == 'a') {
echo key($array).',';
}
}
and I got
1,1,1,
as the result.
If you would like all of the keys for a particular value, I would suggest using array_keys, using the optional search_value parameter.
$input = array("Foo" => "X", "Bar" => "X", "Fizz" => "O");
$result = array_keys( $input, "X" );
Where $result becomes
Array (
[0] => Foo
[1] => Bar
)
If you wish to use a foreach, you can iterate through each key/value set, adding the key to a new array collection when its value matches your search:
$array = array("a","b","c","d","a","a");
$keys = array();
foreach ( $array as $key => $value )
$value === "a" && array_push( $keys, $key );
Where $keys becomes
Array (
[0] => 0
[1] => 4
[2] => 5
)
You can use the below to print out keys with specific value
foreach ($array as $key=>$val) {
if ($val == 'a') {
echo $key." ";
}
}
here's a simpler filter.
$query = "a";
$result = array_keys(array_filter($array,
function($element)use($query){
if($element==$query) return true;
}
));
use
foreach($array as $key=>$val)
{
//access the $key as key.
}
I am sure that this is super easy and built-in function in PHP, but I have yet not seen it.
Here's what I am doing for the moment:
foreach($array as $key => $value) {
echo $key; // Would output "subkey" in the example array
print_r($value);
}
Could I do something like the following instead and thereby save myself from writing "$key => $value" in every foreach loop? (psuedocode)
foreach($array as $subarray) {
echo arrayKey($subarray); // Will output the same as "echo $key" in the former example ("subkey"
print_r($value);
}
Thanks!
The array:
Array
(
[subKey] => Array
(
[value] => myvalue
)
)
You can use key():
<?php
$array = array(
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4
);
while($element = current($array)) {
echo key($array)."\n";
next($array);
}
?>
Use the array_search function.
Example from php.net
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');
foreach($foo as $key => $item) {
echo $item.' is begin with ('.$key.')';
}
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
If it IS a foreach loop as you have described in the question, using $key => $value is fast and efficient.
If you want to be in a foreach loop, then foreach($array as $key => $value) is definitely the recommended approach. Take advantage of simple syntax when a language offers it.
Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)
Try this
foreach(array_keys($array) as $nmkey)
{
echo $nmkey;
}
Here is a generic solution that you can add to your Array library. All you need to do is supply the associated value and the target array!
PHP Manual: array_search() (similiar to .indexOf() in other languages)
public function getKey(string $value, array $target)
{
$key = array_search($value, $target);
if ($key === null) {
throw new InvalidArgumentException("Invalid arguments provided. Check inputs. Must be a (1) a string and (2) an array.");
}
if ($key === false) {
throw new DomainException("The search value does not exists in the target array.");
}
return $key;
}
In an array such as the one below, how could I rename "fee_id" to "id"?
Array
(
[0] => Array
(
[fee_id] => 15
[fee_amount] => 308.5
[year] => 2009
)
[1] => Array
(
[fee_id] => 14
[fee_amount] => 308.5
[year] => 2009
)
)
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['fee_id'];
unset($array[$k]['fee_id']);
}
This should work
You could use array_map() to do it.
$myarray = array_map(function($tag) {
return array(
'id' => $tag['fee_id'],
'fee_amount' => $tag['fee_amount'],
'year' => $tag['year']
); }, $myarray);
$arrayNum = count($theArray);
for( $i = 0 ; $i < $arrayNum ; $i++ )
{
$fee_id_value = $theArray[$i]['fee_id'];
unset($theArray[$i]['fee_id']);
$theArray[$i]['id'] = $fee_id_value;
}
This should work.
Copy the current 'fee_id' value to a new key named 'id' and unset the previous key?
foreach ($array as $arr)
{
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
There is no function builtin doing such thin afaik.
This is the working solution, i tested it.
foreach ($myArray as &$arr) {
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
The snippet below will rename an associative array key while preserving order (sometimes... we must). You can substitute the new key's $value if you need to wholly replace an item.
$old_key = "key_to_replace";
$new_key = "my_new_key";
$intermediate_array = array();
while (list($key, $value) = each($original_array)) {
if ($key == $old_key) {
$intermediate_array[$new_key] = $value;
}
else {
$intermediate_array[$key] = $value;
}
}
$original_array = $intermediate_array;
Converted 0->feild0, 1->field1,2->field2....
This is just one example in which i get comma separated value in string and convert it into multidimensional array and then using foreach loop i changed key value of array
<?php
$str = "abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu;
echo '<pre>';
$arr1 = explode("\n", $str); // this will create multidimensional array from upper string
//print_r($arr1);
foreach ($arr1 as $key => $value) {
$arr2[] = explode(",", $value);
foreach ($arr2 as $key1 => $value1) {
$i =0;
foreach ($value1 as $key2 => $value2) {
$key3 = 'field'.$i;
$i++;
$value1[$key3] = $value2;
unset($value1[$key2]);
}
}
$arr3[] = $value1;
}
print_r($arr3);
?>
I wrote a function to do it using objects or arrays (single or multidimensional) see at https://github.com/joaorito/php_RenameKeys.
Bellow is a simple example, you can use a json feature combine with replace to do it.
// Your original array (single or multi)
$original = array(
'DataHora' => date('YmdHis'),
'Produto' => 'Produto 1',
'Preco' => 10.00,
'Quant' => 2);
// Your map of key to change
$map = array(
'DataHora' => 'Date',
'Produto' => 'Product',
'Preco' => 'Price',
'Quant' => 'Amount');
$temp_array = json_encode($original);
foreach ($map AS $k=>$v) {
$temp_array = str_ireplace('"'.$k.'":','"'.$v.'":', $temp);
}
$new_array = json_decode($temp, $array);
Multidimentional array key can be changed dynamically by following function:
function change_key(array $arr, $keySetOrCallBack = [])
{
$newArr = [];
foreach ($arr as $k => $v) {
if (is_callable($keySetOrCallBack)) {
$key = call_user_func_array($keySetOrCallBack, [$k, $v]);
} else {
$key = $keySetOrCallBack[$k] ?? $k;
}
$newArr[$key] = is_array($v) ? array_change_key($v, $keySetOrCallBack) : $v;
}
return $newArr;
}
Sample Example:
$sampleArray = [
'hello' => 'world',
'nested' => ['hello' => 'John']
];
//Change by difined key set
$outputArray = change_key($sampleArray, ['hello' => 'hi']);
//Output Array: ['hi' => 'world', 'nested' => ['hi' => 'John']];
//Change by callback
$outputArray = change_key($sampleArray, function($key, $value) {
return ucwords(key);
});
//Output Array: ['Hello' => 'world', 'Nested' => ['Hello' => 'John']];
I have been trying to solve this issue for a couple hours using recursive functions, but finally I realized that we don't need recursion at all. Below is my approach.
$search = array('key1','key2','key3');
$replace = array('newkey1','newkey2','newkey3');
$resArray = str_replace($search,$replace,json_encode($array));
$res = json_decode($resArray);
On this way we can avoid loop and recursion.
Hope It helps.
Here's a code example:
$array = array();
$array['master']['slave'] = "foo";
foreach ($array as $key => $value) {
foreach ($value as $key2 => $value2) {
if (preg_match('/slave/',$key2)) {
$value[$key2] = "bar";
print "$value[$key2] => $key2 => $value2\n";
}
}
}
print_r($array);
Output:
bar => slave => foo
Array
(
[master] => Array
(
[slave] => foo
)
)
Rather i would like to have the following as the final array:
Array
(
[master] => Array
(
[slave] => bar
)
)
What wrong am i doing here?
Thank you!
Note:
Example2:
$a= array('l1'=>array('l2'=>array('l3'=>array('l4'=>array('l5'=>'foo')))));
$a['l1']['l2']['l3']['l4']['l5'] = 'bar';
foreach ($a as $i => &$values) {
foreach ( $values as $key => &$value) {
if (is_array($value)){
print_array($value,$key);
}
}
}
function print_array ($Array, $parent) {
foreach ($Array as $i1 => &$values1) {
if (is_array($values1)){
foreach ($values1 as $key1 => &$value1) {
if (is_array($value1)) {
print_array($value1,$values1);
}
else {
print " $key1 => $value1\n";
}
}
}
else {
if (preg_match('/l5/',$i1)) {
$values1 = "foobar";
print " $i1 => $values1\n";
}
}
}
}
print_r($a);
Output does not reflect 'foobar' in l5
Because foreach operates on a copy of the array. Read the documentation about foreach:
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
So you should do
foreach ($array as $key => &$value) {
foreach ($value as $key2 => $value2) {
//...
}
}
Update:
Ok, I reviewed your code again:
Your code was not working as your loops never reach the array with key l5.
The code is highly inefficient. You make assumptions about the depth of the input array. E.g. your code cannot process the input array you provide (it should work if you omit one array).
Solution:
Make use of recursion. This code works:
$a =array('l1'=>array('l2'=>array('l3'=>array('l4'=>array('l5'=>'foo')))));
function process(&$array, $needle) {
foreach($array as $k => &$v) {
if ($k == $needle) {
$v = "boooooooooo";
print "$k => $v\n";
}
if (is_array($v)) {
process($v, $needle);
}
}
}
process($a, $needle);
print_r($a);
Hope that helps.
Oh and please use other keys next time. I thought the whole time that the key was 15 (fifteen) and was wondering why my example was not working ;) (15 looks not that different from l5 at a glance).
You have a few choices, but all stem from the same problem, which originates on this line
foreach ($array as $key => $value) {
At this point in the code, $value is not a reference to 2nd dimension of arrays in your data structure. To fix this, you have a couple options.
1) Force a reference
foreach ($array as $key => &$value) {
2) Use a "fully-qualified" expression to set the desired value
$array[$key][$key2] = 'bar';
Because $value is a new variable
Why not just:
foreach ($array as $key => &$value)
{
if(isset($value['slave']))
$value['slave'] = 'bar';
};