php - foreach through multidimentional array pass by reference on sub values - php

So lets say I have a multidimentional array as such
$myArray = [
0 = [
fruit = 'apple',
juice = 'orange',
cars = [bmw = 'blue', audi = 'red', ford = 'yellow']
],
1 = [
fruit = 'strawberry',
juice = 'grape',
cars = [bmw = 'grey', mazda = 'blue', hummer = 'orange']
],
]
and some replacement array values for cars
$replaceCarsArray = [ferrari = 'red', lamborghini = 'blue, masarati = 'pink']
I foreach through the array with $key => &$values (value being passed by reference)
foreach ($myArray as $key => &$values) {
foreach ($values as $key2 => &$value) {
if ($key2 == 'cars'){
$value = $replaceCarsArray;
}
}
}
that works and replaces the entire cars values with the $replaceCarsArray
but what if I want to target one of the items in that cars array and change the color? So this is what I tried:
foreach ($myArray as $key => &$values) {
foreach ($values as $key2 => &$value) {
if ($key2 == 'cars' && $value['bmw'] != 'red'){
$value['bmw'] = 'red';
}
}
}
this however does not seem to work and the bmw color does not get updated to red. How would I be able to change that data?
Note this is example data and I wrote it very quickly for all intents and purposes I do have access to all of the values and I do not have any syntactical errors in my code as might have appeared here.

Try the following
$myArray[$key][$key2]['bmw'] = 'blue';

That worked for me
<?php
$myArray = [
0 => [
'fruit' => 'apple',
'juice' => 'orange',
'cars' => ['bmw' => 'blue', 'audi' => 'red', 'ford' => 'yellow']
],
1 => [
'fruit' => 'strawberry',
'juice' => 'grape',
'cars' => ['bmw' => 'grey', 'mazda' => 'blue', 'hummer' => 'orange']
]
];
echo "<pre>";
var_dump($myArray);
echo "</pre>";
foreach ($myArray as $key => &$values) {
foreach ($values as $key2 => &$value) {
if ($key2 == 'cars' && $value['bmw'] != 'red'){
$value['bmw'] = 'red';
}
}
}
echo "<pre>";
var_dump($myArray);
echo "</pre>";
echo $myArray[0]['cars']['ford'];
echo $myArray[0]['cars']['bmw'];
tested on : http://phptester.net/

Related

How to create dynamic combination with php?

I have 3 array like
$arr = [
"color" => [["name"=>"red"]],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]]
]
$combo = array();
foreach ($arr['size'] as $size) {
foreach($arr['color'] as $color){
foreach ($arr['type'] as $type) {
$variant = json_encode(['size' => $size->name, 'color' =>
$color->name, 'type' => $type->name]);
array_push($combo,$variant);
}
}
}
echo $combo;
// result
0 => "{"size":"15 inch","color":"yellow","type":"metal"}"
1 => "{"size":"18 inch","color":"yellow","type":"plastic"}"
It works properly but but there is can be less or more variants. How can I handle this.
For example
$arr = [
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]]
]
Or
$arr = [
"color" => [["name"=>"red"]],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]],
"brand" => [['name' => 'something']],
]
For what i understand, you have to combine the arrays of properties into one array of
object.
I have to leave now, but if you need a explanation leave a comment and i updated the answers
$arr = [
"color" => [["name"=>"red"],['name'=>'yellow']],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]],
"brand" => [['name' => 'something']],
];
function runFor($arr ,&$array, $keys,$index,&$positions){
foreach ($arr[$keys[$index]] as $key => $espec){
$positions[$keys[$index]] = $key;
if($index + 1 < count($keys)){
runFor($arr,$array,$keys, $index+1,$positions);
}else{
$item = (object)[];
foreach ($keys as $key){
$item->$key = $arr[$key][$positions[$key]]['name'];
}
array_push($array,$item);
}
unset($positions[$keys[$index]]);
}
}
$array = array();
$keys = array_keys($arr);
$positions = [];
runFor($arr,$array,$keys,0,$positions);
$combo = array();
foreach ($array as $item){
array_push($combo,json_encode($item));
}
var_dump($combo);

PHP: Link address of multiple array keys into another bigger array

I want to combine 3 small arrays that have unique keys between them into 1 big array but when I modify a value in the big array I want it also to reflect in the corresponding small array.
For example I have these 3 small arrays:
$arr1 = ['key1' => 'data1', 'key2' => 'data2'];
$arr2 = ['key3' => 'data3', 'key4' => 'data4', 'key5' => 'data5'];
$arr3 = ['key6' => 'data6'];
I want to have a $bigArray that has each key's address linked/mapped to each value of the small arrays. So if I do something like:
$bigArray['key4'] = 'something else';
then it would modify $arr2['key4'] to the same value ('something else').
If I try something like:
$bigArray = [&$arr1, &$arr2, &$arr3];
It has the unfortunate effect of making a multidimensional array with the keys to the values mapped.
Two ways i found
<?php
error_reporting(E_ALL);
$arr1 = ['key1' => 'data1', 'key2' => 'data2'];
$arr2 = ['key3' => 'data3', 'key4' => 'data4', 'key5' => 'data5'];
$arr3 = ['key6' => 'data6'];
$big = [];
if (true) {
foreach (['arr1', 'arr2', 'arr3'] as $v) {
foreach (array_keys($$v) as $k) {
$big[$k] = &${$v}[$k];
}
}
}
else {
foreach ([&$arr1, &$arr2, &$arr3] as &$v) {
foreach (array_keys($v) as $k) {
$big[$k] = &$v[$k];
}
}
}
$big['key1'] = 'data1mod';
print_r($big);
print_r($arr1);
3rd way with function
$big = [];
$bindToBig = function (&$a) use (&$big) {
foreach (array_keys($a) as $k) {
$big[$k] = &$a[$k];
}
};
$bindToBig($arr1);
$bindToBig($arr2);
$bindToBig($arr3);
You can't bind data that way, but you can link them in the same object:
class ArrayLink {
public $bigArray;
public $linkedChildrenArray;
protected $childrenArray;
public function __construct( $childrenArray ) {
$this->childrenArray = $childrenArray;
}
public function changeValueForKey( $arrKey, $arrValue ) {
foreach ( $this->childrenArray as $key => $value ) {
foreach ( $value as $subKey => $subValue ) {
if ( $arrKey == $subKey ) {
$this->bigArray[ $subKey ] = $arrValue;
$this->childrenArray[ $key ][ $subKey ] = $arrValue;
}
}
}
$this->linkedChildrenArray = (object) $this->childrenArray;
}
}
As you can see, the $arr2 now need to be access from $arrayLink object:
$arr1 = [ 'key1' => 'data1', 'key2' => 'data2' ];
$arr2 = [ 'key3' => 'data3', 'key4' => 'data4', 'key5' => 'data5' ];
$arr3 = [ 'key6' => 'data6' ];
$arrayLink = new ArrayLink( array( 'arr1' => $arr1, 'arr2' => $arr2, 'arr3' => $arr3 ) );
$arrayLink->changeValueForKey( 'key3', 'new value for key 3' );
echo $arrayLink->bigArray['key3']; //new value for key 3
echo $arrayLink->linkedChildrenArray->arr2['key3']; //new value for key 3

Get all values from multidimensional array

Let's say, I have an array like this:
$array = [
'car' => [
'BMW' => 'blue',
'toyota' => 'gray'
],
'animal' => [
'cat' => 'orange',
'horse' => 'white'
]
];
Then, I want to get all the values (the colour, 'blue', 'gray', 'orange', 'white') and join them into a single array. How do I do that without using foreach twice?
Thanks in advance.
TL;DR
$result = call_user_func_array('array_merge', $array);
Credit: How to "flatten" a multi-dimensional array to simple one in PHP?
In your use case, you should use it like this:
<?php
$array = [
'car' => [
'BMW' => 'blue',
'toyota' => 'gray'
],
'animal' => [
'cat' => 'orange',
'horse' => 'white'
]
];
$result = call_user_func_array('array_merge', $array);
$result = array_values($result);
//$result = ['blue', 'gray', 'orange', 'white']
Old but as far i see not really a "working on all cases" function posted.
So here is the common classic recursively function:
function getArrayValuesRecursively(array $array)
{
$values = [];
foreach ($array as $value) {
if (is_array($value)) {
$values = array_merge($values,
getArrayValuesRecursively($value));
} else {
$values[] = $value;
}
}
return $values;
}
Example array:
$array = [
'car' => [
'BMW' => 'blue',
'toyota' => 'gray'
],
'animal' => [
'cat' => 'orange',
'horse' => 'white'
],
'foo' => [
'bar',
'baz' => [
1,
2 => [
2.1,
'deep' => [
'red'
],
2.2,
],
3,
]
],
];
Call:
echo var_export(getArrayValuesRecursively($array), true) . PHP_EOL;
Result:
// array(
// 0 => 'blue',
// 1 => 'gray',
// 2 => 'orange',
// 3 => 'white',
// 4 => 'bar',
// 5 => 1,
// 6 => 2.1,
// 7 => 'red',
// 8 => 2.2,
// 9 => 3,
// )
Try this:
function get_values($array){
foreach($array as $key => $value){
if(is_array($array[$key])){
print_r (array_values($array[$key]));
}
}
}
get_values($array);
How do I do that without using foreach twice?
First use RecursiveIteratorIterator class to flatten the multidimensional array, and then apply array_values() function to get the desired color values in a single array.
Here are the references:
RecursiveIteratorIterator class
array_values()
So your code should be like this:
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$flatten_array = array_values(iterator_to_array($iterator,true));
// display $flatten_array
echo "<pre>"; print_r($flatten_array);
Here's the live demo
Here's a recursive function that gives you both the ability to get an array of those endpoint values, or to get an array with all keys intact, but just flattened.
Code:
<?php
$array = [
'car' => [
'BMW' => 'blue',
'toyota' => 'gray'
],
'animal' => [
'cat' => 'orange',
'horse' => 'white'
]
];
//
print "\n<br> Array (Original): ".print_r($array,true);
print "\n<br> Array (Flattened, With Keys): ".print_r(FlattenMultiArray($array,true),true);
print "\n<br> Array (Flattened, No Keys): ".print_r(FlattenMultiArray($array,false),true);
//
function FlattenMultiArray($array,$bKeepKeys=true,$key_prefix='')
{
//
$array_flattened=Array();
//
foreach($array as $key=>$value){
//
if(Is_Array($value)){
$array_flattened=Array_Merge(
$array_flattened,
FlattenMultiArray($value,$bKeepKeys,$key)
);
}
else{
if($bKeepKeys){
$array_flattened["{$key_prefix}_{$key}"]=$value;
}
else{
$array_flattened[]=$value;
}
}
}
return $array_flattened;
}
?>
Outputs:
<br> Array (Original): Array
(
[car] => Array
(
[BMW] => blue
[toyota] => gray
)
[animal] => Array
(
[cat] => orange
[horse] => white
)
)
<br> Array (Flattened, With Keys): Array
(
[car_BMW] => blue
[car_toyota] => gray
[animal_cat] => orange
[animal_horse] => white
)
<br> Array (Flattened, No Keys): Array
(
[0] => blue
[1] => gray
[2] => orange
[3] => white
)
If you don't care about the indexes, then this should do it:
$colors = array();
foreach ($array as $item) {
$colors = array_merge($colors, array_values($item));
}
If you want to keep the indexes you could use:
$colors = array();
foreach ($array as $item) {
// this leaves you open to elements overwriting each other depending on their keys
$colors = array_merge($colors, $item);
}
I hope this helps.
what about this one?It works with ANY array depth.
private function flattenMultiArray($array)
{
$result = [];
self::flattenKeyRecursively($array, $result, '');
return $result;
}
private static function flattenKeyRecursively($array, &$result, $parentKey)
{
foreach ($array as $key => $value) {
$itemKey = ($parentKey ? $parentKey . '.' : '') . $key;
if (is_array($value)) {
self::flattenKeyRecursively($value, $result, $itemKey);
} else {
$result[$itemKey] = $value;
}
}
}
P.S. solution is not mine, but works perfectly, and I hope it will help someone.
Original source:
https://github.com/letsdrink/ouzo/blob/master/src/Ouzo/Goodies/Utilities/Arrays.php

Loop array content value consist of single value and array

I have tried to loop this array but I still get error
I have an array like this:
1 => ["name"=>"A", "related"=>[
["signal"=>"A1", "color"=>"green"],
["signal"=>"A2", "color"=>"lime"],
["signal"=>"A3","color"=>"yellowGreen"]
]]
2 => ["name"=>"B", "related"=>[
["signal"=>"B1", "color"=>"Red"],
["signal"=>"B2", "color"=>"Pink"]
]]
How to display as - A : Green, lime, yellowGreeb
- B : Red, Pink
This is my code that I've tried to display as above format
foreach($arr as $key => $value){
echo $value["name"];
foreach($value["related"] as $k){
echo $k["color"] . ",";
}
}
It throw error this array dont has $value["related"] index. But It can echo the $value["name"]???
Thank you!
Find the solution as below:
$array = [1 => [
"name" => "A",
"related" => [
["signal" => "A1", "color" => "green"],
["signal" => "A2", "color" => "lime"],
["signal" => "A3", "color" => "yellowGreen"]
]
],
2 => ["name" => "B", "related" => [
["signal" => "B1", "color" => "Red"],
["signal" => "B2", "color" => "Pink"]
]]
];
foreach ($array as $ar) {
$new_arr = array_column($ar['related'], 'color');
$required_string = implode(', ', $new_arr);
echo $ar['name'].' : ' .$required_string;
echo "<br />";
}
For PHP Version < 5.5 you can use below solution:
foreach ($array as $ar) {
$new_arr = array_map(function ($value) {
return $value['color'];
}, $ar['related']);
$required_string = implode(', ', $new_arr);
echo $ar['name'].' : ' .$required_string;
echo "<br />";
}
you can found more detail about foreach loop at http://php.net/manual/en/control-structures.foreach.php

PHP : multidimensional array merge recursive

I need to merge those two arrays:
$ar1 = array("color" => array("red", "green"), "aa");
$ar2 = array("color" => array( "green", "blue"), "bb");
$result = array_merge_recursive($ar1, $ar2);
Expected output:
[
'color' => [
(int) 0 => 'red',
(int) 1 => 'green',
(int) 3 => 'blue'
],
(int) 0 => 'aa',
(int) 1 => 'bb'
]
But it outputs:
[
'color' => [
(int) 0 => 'red',
(int) 1 => 'green',
(int) 2 => 'green', (!)
(int) 3 => 'blue'
],
(int) 0 => 'aa',
(int) 1 => 'bb'
]
I'm looking for the simplest way to do this, my array inputs won't be deeper than those examples.
Here it is.
function array_merge_recursive_ex(array $array1, array $array2)
{
$merged = $array1;
foreach ($array2 as $key => & $value) {
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = array_merge_recursive_ex($merged[$key], $value);
} else if (is_numeric($key)) {
if (!in_array($value, $merged)) {
$merged[] = $value;
}
} else {
$merged[$key] = $value;
}
}
return $merged;
}
Thanks to Meglio comment, you can use these functions for any number of arrays :
Functions
function drupal_array_merge_deep() {
$args = func_get_args();
return drupal_array_merge_deep_array($args);
}
// source : https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_array_merge_deep_array/7.x
function drupal_array_merge_deep_array($arrays) {
$result = array();
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
// Renumber integer keys as array_merge_recursive() does. Note that PHP
// automatically converts array keys that are integer strings (e.g., '1')
// to integers.
if (is_integer($key)) {
$result[] = $value;
}
elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
$result[$key] = drupal_array_merge_deep_array(array(
$result[$key],
$value,
));
}
else {
$result[$key] = $value;
}
}
}
return $result;
}
Usage
$merged = drupal_array_merge_deep($ar_1, $ar_2);
var_dump($merged);
$merged = drupal_array_merge_deep_array([$ar_1, $ar_2]);
var_dump($merged);
Usage (test data)
$ar_1 = [
"item1" => false,
"item2" => true,
"item_list" => [
"sub_item1" => 5,
"sub_itemlist" => [
"sub_sub_item1" => 27,
],
]
];
$ar_2 = [
"item_list" => [
"sub_item2" => 5,
"sub_itemlist" => [
"sub_sub_item2" => 27,
],
],
"item3" => true,
];
Usage output (same for both functions)
array (size=4)
'item1' => boolean false
'item2' => boolean true
'item_list' =>
array (size=3)
'sub_item1' => int 5
'sub_itemlist' =>
array (size=2)
'sub_sub_item1' => int 27
'sub_sub_item2' => int 27
'sub_item2' => int 5
'item3' => boolean true

Categories