Pushing multidimensional arrays as keys on another array - php

I have an empty array (as an example) and a number of multidimensional arrays I would like to push onto this array. However I would like the keys of each multidimensional array to become a key of the empty array
Using
$myEmptyArray[] = $arrayOne;
$myEmptyArray[] = $arrayTwo;
$myEmptyArray[] = $arrayThree;
I get
[
0 => ['one' => ['a' => 'stuff']],
1 => ['two' => ['b' => 'stuff']],
2 => ['three' => ['c' => 'stuff']]
]
I would prefer to have
[
'one' => ['a' => 'stuff'],
'two' => ['b' => 'stuff'],
'three' => ['c' => 'stuff']
]
What is a neat and compact way (one liner or native php function) to do this without having to read the array key with a foreach and then assign this key explicitly to the empty array with the value like
foreach ($arrayOne as $key => $value) {
$myEmptyArray[$key] = $value
}
As I will want to use this in many places in my code

You can use the + (union) operator which "returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored".
$array = [];
$array += ['one' => ['a' => 'stuff']];
$array += ['two' => ['b' => 'stuff']];
$array += ['three' => ['b' => 'stuff']];
var_dump($array);
/*
array(3) {
'one' =>
array(1) {
'a' =>
string(5) "stuff"
}
'two' =>
array(1) {
'b' =>
string(5) "stuff"
}
'three' =>
array(1) {
'b' =>
string(5) "stuff"
}
}
*/

You can simply use + to combine those array in the way you want:
$arrayOne = array('one' => array('a' => 'stuff'));
$arrayTwo = array('two' => array('b' => 'stuff'));
$arrayThree = array('three' => array('c' => 'stuff'));
$myEmptyArray = array();
$myEmptyArray += $arrayOne;
$myEmptyArray += $arrayTwo;
$myEmptyArray += $arrayThree;
echo "<pre>"; print_r($myEmptyArray); echo "</pre>";
OUTPUT:
Array
(
[one] => Array
(
[a] => stuff
)
[two] => Array
(
[b] => stuff
)
[three] => Array
(
[c] => stuff
)
)

Related

Zip multiple arrays in PHP based on their identical keys and not their indices or their positions in array

I have two arrays:
$a = ['one'=>1,'two'=> 2,'three'=> 3,'four'=> 4,'five'=> 5, 'six' => 6];
$b = ['one'=>'uno', 'three'=>'tres','two'=> 'dos', 'four'=>'cuatro', 'five'=>'cinco'];
note that in $b Array 'three' and 'two' keys are not in same order as $a. also 'six' key is not available in $b Array.
I want this result as output:
Array
(
[0] => Array
(
[0] => 1
[1] => uno
)
[1] => Array
(
[0] => 2
[1] => dos
)
[2] => Array
(
[0] => 3
[1] => tres
)
[3] => Array
(
[0] => 4
[1] => cuatro
)
[4] => Array
(
[0] => 5
[1] => cinco
)
)
I tried to use array_map but it don't detect keys and just zip them based of their indices:
$d = array_map(null, $a, $b);
Can't you just use ksort(). Then, create a new array using `foreach'?
An example using foreach
<?php
$a = ['one' => 1, 'two' => 2, 'three' => 3, 'four' => 4, 'five' => 5];
$b = ['one' => 'uno', 'three' => 'tres', 'two' => 'dos', 'four' => 'cuatro', 'five' => 'cinco'];
$output = [];
foreach ($a as $key => $value) {
$output[] = [$value, $b[$key]];
}
print_r($output);
modified ikhvjs answer (when keys in both arrays are not same as each others):
$a = ['one' => 1, 'two' => 2, 'four' => 4, 'five' => 5, 'six' => 6];
$b = ['one' => 'uno', 'three' => 'tres', 'two' => 'dos', 'four' => 'cuatro', 'five' => 'cinco'];
$r=array_intersect_key($a,$b);
$output = [];
foreach ($r as $key => $value) {
$output[] = [$value, $b[$key]];
}
echo "<pre>";
print_r($output);
echo "</pre>";
I must say #ikhvjs's answer is the closest to perfect, but the $b array doesn't have a value with the key six. To accommodate the possibility of elements in $b not relating to elements in $a, use the null coalescing operator to fallback to a null value.
As for the mentioning of ksort(), this will do nothing to accommodate the fact that the input arrays have different lengths / keys.
The use of array_intersect_key() will result in $a values being omitted where not related to an element in $b.
If $a is not a reliable "master" array (with all possible keys), then you will need to loop a temporary array formed by merging the two arrays and implement the null coalescing operator on both values to be pushed into the result array.
Code: (Demo) (Demo of null coalescing on both values)
$a = [
'one' => 1,
'two' => 2,
'three' => 3,
'four' => 4,
'five' => 5,
'six' => 6
];
$b = [
'one' => 'uno',
'three' => 'tres',
'two' => 'dos',
'four' => 'cuatro',
'five' => 'cinco'
];
$result = [];
foreach ($a as $k => $v) {
$result[] = [$v, $b[$k] ?? null];
}
var_export($result);
Output:
array (
0 =>
array (
0 => 1,
1 => 'uno',
),
1 =>
array (
0 => 2,
1 => 'dos',
),
2 =>
array (
0 => 3,
1 => 'tres',
),
3 =>
array (
0 => 4,
1 => 'cuatro',
),
4 =>
array (
0 => 5,
1 => 'cinco',
),
5 =>
array (
0 => 6,
1 => NULL,
),
)

php: combine multiple arrays value into one array preserving keys

I have multiple arrays structured like these:
$array1 = ["aaa" => 1, "bbb" => 1];
$array2 = ["aaa" => 12, "bbb" => 12];
$array3 = ["bbb" => 15, "ccc" => 15];
meaning:
every array has the same value for each key (eg: array1 has value "1" for every item in the array) but there are no arrays sharing the same value (eg: if array1 has value 1, then none of the other arrays has value = 1)
the arrays may or may not share the same keys
I need to combine these arrays in a way that the final result is something like this:
$result = [
"aaa" => [1,12],
"bbb" => [1,12,15],
"ccc" => [15],
];
meaning:
the final array must contain all the keys from the previous arrays
the value of the key is an array composed of all the values of the previous arrays that shared the same key
I know it's a bit messy, but I hope it is clear enough. I'm struggling to build the $result array. I tried merge, combine, intersect, but none of them seems to work. Is there a way to build the $result array without using a loop?
Thanks
Does it match your goal ?
<?php
$array1 = ["aaa" => 1, "bbb" => 1];
$array2 = ["aaa" => 12, "bbb" => 12];
$array3 = ["bbb" => 15, "ccc" => 15];
$array = array_merge_recursive($array1, $array2, $array3);
print_r($array);
?>
outputs
Array
(
[aaa] => Array
(
[0] => 1
[1] => 12
)
[bbb] => Array
(
[0] => 1
[1] => 12
[2] => 15
)
[ccc] => 15
)
Merge all of array into an mergedArray. Then use 2 foreach to set it.
<?php
$array1 = ["aaa" => 1, "bbb" => 1];
$array2 = ["aaa" => 12, "bbb" => 12];
$array3 = ["bbb" => 15, "ccc" => 15];
$mergedArray = [$array1, $array2, $array3];
$result = [];
foreach ($mergedArray as $array) {
foreach ($array as $key => $item) {
$result[$key][] = $item;
}
}
echo '<pre>';
print_r($result);
echo '</pre>';
exit;
?>
The result:
Array
(
[aaa] => Array
(
[0] => 1
[1] => 12
)
[bbb] => Array
(
[0] => 1
[1] => 12
[2] => 15
)
[ccc] => Array
(
[0] => 15
)
)

Comparing two arrays php with a third array

I have two arrays with the year's results.
array A (
[a] => '150'
[b] => '200'
[c] => '300'
[d] => '1000'
[e] => '350'
[f] => '1000'
)
array B (
[a] => '500'
[b] => '400'
[d] => '1000'
[f] => '1000'
)
I need to compare the growth results between the two building another array, to show it in a html table. Ex:
[a] => 233%
[b] => 100%
...
I have a array identifying the indexes that are not present on array b.
array c = ('c', 'e');
The thing is, I need the row C and E to still be displayed on the table. But on the iteration, how can i just jump the line with this indexes that have 0 value avoiding calculation 300 by 0 and putting a message instead?
You can iterate the first array and check the next one values:
$arrayA = [
'a' => '150',
'b' => '200',
'c' => '300',
'd' => '1000',
'e' => '350',
'f' => '1000',
];
$arrayB = [
'a' => '500',
'b' => '400',
'd' => '1000',
'f' => '1000',
];
$result = [];
foreach ($arrayA as $key => $value) {
if(isset($arrayB[$key])) {
$result[$key] = round($arrayB[$key] * 100 / $value, 2);
} else {
$result[$key] = 'some value when empty';
}
}
var_dump($result);
Output:
array(6) {
["a"]=>
float(333.33)
["b"]=>
float(200)
["c"]=>
string(21) "some value when empty"
["d"]=>
float(100)
["e"]=>
string(21) "some value when empty"
["f"]=>
float(100)
}
You could loop through array A and check if the key of array A exists in array B using array_key_exists and then calculate the growth percentage:
$arrayA = [
'a' => '150',
'b' => '200',
'c' => '300',
'd' => '1000',
'e' => '350',
'f' => '1000'
];
$arrayB = [
'a' => '500',
'b' => '400',
'd' => '1000',
'f' => '1000'
];
$arrayC = [];
foreach($arrayA as $keyA => $valueA) {
if (array_key_exists($keyA, $arrayB)) {
$arrayC[$keyA] = floor((($arrayB[$keyA] - $valueA) / $valueA ) * 100) . "%";
continue;
}
$arrayC[$keyA] = "No match";
}
Result
Array
(
[a] => 233%
[b] => 100%
[c] => No match
[d] => 0%
[e] => No match
[f] => 0%
)
Demo
If you want a more flexible solution where you can check for both values of the two arrays (i.e. do not base the comparison keys on a single array) and have the possibility to expand it for more than two arrays (it may be useful to others who do not have your same goal).
Fetch the keys of the two array with array_keys and use array_unique in order to avoid duplicate keys values.
<?php
$array_a = [
'a' => 150,
'b' => 200,
'c' => 300,
'd' => 1000,
'e' => 350,
'f' => 1000
];
$array_b = [
'a' => 500,
'b' => 400,
'd' => 1000,
'f' => 1000
];
$keys_a = array_keys($array_a);
$keys_b = array_keys($array_b);
$keys = array_unique(array_merge($keys_a, $keys_b));
$result = [];
foreach ($keys as $key)
{
if (isset($array_a[$key]) && isset($array_b[$key]))
{
$result[$key] = round((($array_b[$key] - $array_a[$key]) / $array_a[$key]) * 100);
}
else
{
$result[$key] = "missing key in one of the two arrays";
}
}
Output:
Array
(
[a] => 233
[b] => 100
[c] => missing key in one of the two arrays
[d] => 0
[e] => missing key in one of the two arrays
[f] => 0
)

Array remapping - Can I do this better?

for starters I have the following array objects (id, foo and bar are a result of a database query and should be addressed as object variables ->id)
array([0] => array([id] => 1, [foo] => 'a'), [1] => array([id] => 2, [foo] => 'b')
and
array([0] => array([id] => 1, [bar] => 'b'), [1] => array([id] => 2, [bar] => 'a')
I want to create one new array with the id column as key
array([1] => array([foo] => 'a', [bar] => 'b'), [2] => array([foo] => 'b', [bar] => 'a')
I used the following lines of code to create the desired array:
foreach($array1 as $row1) {
$newArray1[$row1->id] = $row1;
}
foreach($array2 as $row2) {
$newArray2[$row2->id] = $row2;
}
foreach($array2 as $key => row3) { //array 2 is always longer or equal to array 1
$result[$key]['bar'] = $newArray2[$key]->bar;
if (isset($newArray1[$key])) {
$result[$key]['foo'] = $newArray1[$key]->foo;
} else {
$result[$key]['bar'] = 0;
}
}
I think this could be done a lot easier. Is this the case, if so, how?
If I understood you need to merge two arrays using as index the 'id' field, which is equal to both ones.
I would do this:
$newarray = array();
for($i=0;$i<count($array1);$i++)
$newarray[$array1[$i]["id"]] = array($array1[$i]["foo"], $array2[$i]["bar"]);
instead of creating new array you can do this:
$arr1=array('0' => array('id' => 1, 'foo' => 'a'), '1' => array('id' => 2, 'foo' => 'b'));
$arr2=array('0' => array('id' => 1, 'bar' => 'b'), '1' => array('id' => 2, 'bar' => 'a'));
for($i=0;$i<count($arr1);$i++){
$arr1[$i] = array("foo"=>$arr1[$i]["foo"], "bar"=>$arr2[$i]["bar"]);
}
print_r($arr1);

Insert key and value into array

I have this code
$array = array('o' => 'one', 't' => 'three', 'f' => 'four');
array_push($array, array('s' => 'six'));
print_r($array);
that insert new key and value into the array , but when i print the new $array it returned this
Array ( [o] => one [t] => three [f] => four [0] => Array ( [s] => six ) )
i need to return like this
Array ( [o] => one [t] => three [f] => four [s] => six )
how to remove [0] => Array () from the array ?
array_push is intended for lists.
$arr = array(5, 6, 7);
array_push($arr, 8); // array(5, 6, 7, 8);
You can add elements to arrays in many ways, this is one:
$array = array('o' => 'one', 't' => 'three', 'f' => 'four');
$array["s"] = "six";
Here is another:
$array = array_merge($array, array("s" => "six"));
PHP treats lists like array(1, 2, 3); differently than associative arrays like array("foo" => "bar");. The differences are minor, but they show up with functions like array_push.

Categories