PHP combine array all array elements - php

Assuming I don't want to loop through and build a new array, is there a built in way in PHP to add two arrays together and push all keys from the second array after the keys from the first? I Googled around and couldn't find anything that does exactly this, but wondering if anyone might know
For example to combine these..
array( 0 => "a", 1 => "b" );
array ( 0 => "c", 1 => "d" );
and get this..
array( 0 => "a", 1 => "b", 2 => "c", 3 => "d" );

This:
array_merge(array( 0 => "a", 1 => "b" ),array ( 0 => "c", 1 => "d" ));
Or
array( 0 => "a", 1 => "b" ) + array ( 0 => "c", 1 => "d" )
This first one will overwrite duplicate keys, the second will not. And you may have to sort the array afterwords.
Or, you could do:
array_merge(array_values(array( 0 => "a", 1 => "b" )), array_values(array ( 0 => "c", 1 => "d" )))
That will definitely work

Take a look at array_merge.
<?php
$ab = array('a', 'b');
$cd = array('c', 'd');
var_dump(
array_merge($ab, $cd)
);
/*
array(4) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
[3]=>
string(1) "d"
}
*/

You could also try:
<?php
$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = array_merge($array1, $array2);
print_r($result);
/*
Array
(
[0] => zero_a
[1] => two_a
[2] => three_a
[3] => one_b
[4] => three_b
[5] => four_b
)
*/
?>
Reference

Related

PHP - Check if array keys matches an array of keys

I have the following array:
"origem_fornecedor" => array:5 [▼
"A" => 50
"B" => 70
"C" => 50
"D" => 85
"E" => 50
]
And I need to check if the keys present in that array matches the values present in this constant:
const NIVEIS = ['A', 'B', 'C', 'D', 'E'];
Arrays that should fail this test:
"origem_fornecedor" => array:2 [▼
"A" => 50
"B" => 70
]
"origem_fornecedor" => array:7 [▼
"A" => 50
"B" => 70
"C" => 50
"D" => 85
"E" => 50
"F" => 95
"G" => 10
]
if ( array_keys($origem_fornecedor) == NIVEIS ) echo "Ok"; else echo "KO";
PS : What's this syntax : "origem_fornecedor" ?

Extending 2 arrays depending on a value

I have two example arrays:
$array1 = array(
0 => array("a" => '123', "b" => 234),
1 => array("a" => 'abs', "b" => 234),
2 => array("a" => '123', "b" => 234),
3 => array("a" => 'abs', "b" => 234),
4 => array("a" => '123', "b" => 234),
5 => array("a" => 'abs', "b" => 898),
6 => array("a" => '123', "b" => 234),
7 => array("a" => 'abs', "b" => 234),
8 => array("a" => '123', "b" => 234),
9 => array("a" => 'abs', "b" => 898)
);
$array2 = array(
0 => array("b" => '234', "c" => "Herr"),
1 => array("b" => '898', "c" => "Frau"),
);
Array 1 should be extended by c, depending on the value in b, which is present in both arrays. Finally, array 1 should look like this:
$array3 = array(
0 => array("a" => '123', "b" => 234, "c" => "Herr"),
1 => array("a" => 'abs', "b" => 234, "c" => "Herr"),
2 => array("a" => '123', "b" => 234, "c" => "Herr"),
3 => array("a" => 'abs', "b" => 234, "c" => "Herr"),
4 => array("a" => '123', "b" => 234, "c" => "Herr"),
5 => array("a" => 'abs', "b" => 898, "c" => "Frau"),
6 => array("a" => '123', "b" => 234, "c" => "Herr"),
7 => array("a" => 'abs', "b" => 234, "c" => "Herr"),
8 => array("a" => '123', "b" => 234, "c" => "Herr"),
9 => array("a" => 'abs', "b" => 898, "c" => "Frau")
);
Are there already simple ways to realize this in PHP7.x?
Make an iteration over $array1 using array_walk(). In use() scope pass the filter array prepared (['234' => 'Herr', '898' => 'Frau']) from $array2. In every cycle of the iteration get value from $filter array by the index value of b and set it to $array1's c index. Example:
$filter = array_column($array2, 'c', 'b');
array_walk($array1, function(&$val) use ($filter) {
$val['c'] = $filter[$val['b']];
});
print_r($array1);
Working demo.
One way of doing it would be a loop through foreach, create an array that contains all the b indexes in $array2 by using array_column(). Then use array_search() on that column, and look for the index b of the current iteration of $array1 - that key (from $array2) will tell you which index to choose. Fetch the value and append it to the temporary array, then append the temporary array into $array3.
$array3 = array();
$b_values = array_column($array2, "b");
foreach ($array1 as $v) {
$temp = $v;
$key_2 = array_search($v['b'], $b_values);
$temp['c'] = $array2[$key_2]['c'];
$array3[] = $temp;
}
Live demo at https://3v4l.org/lZHKS

Return a sub array with two specific key/value pairs

Consider the following array returned from an API:
$arr = Array
(
[A] =>
[C] =>
[D] =>
[EE] => Array
(
[0] => Array
(
[B] =>
[C] => 2.06
[O] =>
[P] => 0
[T] => 1
)
[1] => Array
(
[B] =>
[C] => 2.56
[O] =>
[P] => 0
[T] => 2
)
[2] => Array
(
[B] =>
[C] => 4.94
[O] =>
[P] => 0
[T] => 3
)
[3] => Array
(
[B] =>
[C] => 1.42
[O] =>
[P] => 1
[T] => 9
)
[4] => Array
(
[B] =>
[C] => 2.83
[O] =>
[P] => 1
[T] => 10
)
[5] => Array
(
[B] =>
[C] => 2.13
[O] =>
[P] => 1.5
[T] => 9
)
[6] => Array
(
[B] =>
[C] => 1.7
[O] =>
[P] => 1.5
[T] => 10
)
)
)
I want to get the C value from the sub array where P is 1.5 and T is 9. Obviously if I knew this would always be in sub array with index 5 I could just do this:
$arr['EE'][5]['C'];
But 5 will not always be the index of that particular array. So I'm looking for something more along the lines of:
$arr['EE'][...P is 1.5 and T is 9...]['C'];
This is within a loop that processes thousands of these arrays, so performance is definitely a consideration. In other words, I don't want to do a bunch of nested loops to find that value - I'm looking for a built-in PHP function for this (or a combination thereof) if it exists.
You can also use array_reduce
$arr = array
(
"A" => "",
"C" => "",
"D" => "",
"EE" => array
(
"0" => array
(
"B" => "",
"C" => 2.06,
"O" => "",
"P" => 0,
"T" => 1,
),
"1" => array
(
"B" => "",
"C" => 2.56,
"O" => "",
"P" => 0,
"T" => 2,
),
"2" => array
(
"B" => "",
"C" => 4.94,
"O" => "",
"P" => 0,
"T" => 3,
),
"3" => array
(
"B" => "",
"C" => 1.42,
"O" => "",
"P" => 1,
"T" => 9,
),
"4" => array
(
"B" => "",
"C" => 2.83,
"O" => "",
"P" => 1,
"T" => 10,
),
"5" => array
(
"B" => "",
"C" => 2.13,
"O" => "",
"P" => 1.5,
"T" => 9,
),
"6" => array
(
"B" => "",
"C" => 1.7,
"O" => "",
"P" => 1.5,
"T" => 10,
),
)
);
$p = 1.5;
$t = 9;
$result = array_reduce( $arr["EE"], function( $c, $v ) use ($p,$t) {
if ( $v["P"] == $p && $v["T"] == $t ) $c = $v["C"];
return $c;
}, "" );
echo $result;
This will result to:
2.13
Other option: You can use array_filter
$p = 1.5;
$t = 9;
$result = array_filter( $arr["EE"], function( $v ) use ($p,$t) {
return $v["P"] == $p && $v["T"] == $t;
} );
$result = array_values( $result );
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to
Array
(
[0] => Array
(
[B] =>
[C] => 2.13
[O] =>
[P] => 1.5
[T] => 9
)
)
So accessing C is $result[0]["C"]
Doc: array_filter
Or for performance, you can use foreach loop
$p = 1.5;
$t = 9;
$result = "";
foreach( $arr["EE"] as $v ) {
if ( $v["P"] == $p && $v["T"] == $t ) $result = $v["C"];
}
echo $result;

Sum of duplicate key values array in PHP [duplicate]

This question already has answers here:
How to sum all column values in multi-dimensional array?
(20 answers)
Closed 9 months ago.
I have an array with duplicate key values. How can I sum all duplicate array key values in another new array?
$array = Array (
"0" => Array ( "2" => 123 ),
"1" => Array ( "4" => 45 ),
"2" => Array ( "3" => 12 ),
"3" => Array ( "5" => 2 ),
"4" => Array ( "2" => 12 ),
"5" => Array ( "4" => 21 ),
"6" => Array ( "2" => 12 ),
"7" => Array ( "3" => 21 ),
"8" => Array ( "2" => 12 ),
"9" => Array ( "3" => 21 ),
"10" => Array ( "2" => 2 ),
"11" => Array ( "4" => 2 ),
"12" => Array ( "2" => 2 ),
"13" => Array ( "4" => 2 ),
"14" => Array ( "3" => 12 ),
"15" => Array ( "4" => 12 ),
"16" => Array ( "2" => 12 ),
"17" => Array ( "2" => 12 ),
"18" => Array ( "4" => 12 ),
"19" => Array ( "3" => 12 ),
"20" => Array ( "2" => 15 ),
"21" => Array ( "4" => 21 ),
);
Output will looks like
$newArray = Array
(
[2] => 202
[3] => 78
[4] => 115
[5] => 2
)
You can use array_sum and array_column to get the sums of each.
First we have to get all the keys then sum them with array_sum and array_column.
$arr = Array (
"0" => Array ( "2" => 123 ),
"1" => Array ( "4" => 45 ),
"2" => Array ( "3" => 12 ),
"3" => Array ( "5" => 2 ),
"4" => Array ( "2" => 12 ),
"5" => Array ( "4" => 21 ),
"6" => Array ( "2" => 12 ),
"7" => Array ( "3" => 21 ),
"8" => Array ( "2" => 12 ),
"9" => Array ( "3" => 21 ),
"10" => Array ( "2" => 2 ),
"11" => Array ( "4" => 2 ),
"12" => Array ( "2" => 2 ),
"13" => Array ( "4" => 2 ),
"14" => Array ( "3" => 12 ),
"15" => Array ( "4" => 12 ),
"16" => Array ( "2" => 12 ),
"17" => Array ( "2" => 12 ),
"18" => Array ( "4" => 12 ),
"19" => Array ( "3" => 12 ),
"20" => Array ( "2" => 15 ),
"21" => Array ( "4" => 21 ),
);
// find all subarray keys (2,3,4,5)
foreach($arr as $subarr){
$keys[] = key($subarr);
}
// remove duplicate keys
$keys = array_unique($keys);
// sum values with same key from $arr and save to $sums
foreach($keys as $key){
$sums[$key] = array_sum(array_column($arr,$key));
}
var_dump($sums);
https://3v4l.org/F3RJr
The code can be made shorter like this:
foreach($arr as $subarr){
$key = key($subarr);
if(!isset($sums[$key])){
$sums[$key] = array_sum(array_column($arr,$key));
}
}
var_dump($sums);
but I'm not sure it's faster. Maybe...
You can use array_walk_recursive()
$result = [];
array_walk_recursive($array, function($v, $k) use (&$result) {
if (!isset($result[$k])) {
$result[$k] = $v;
} else {
$result[$k] += $v;
}
});
print_r($result);
Check the below code.
$output = array();
$keyarray = array();
foreach($arr as $key => $val){
if(is_array($val)){
$key = key($val);
if(in_array($key,$keyarray)) {
$output[$key] = $output[$key]+$val[$key];
} else {
$keyarray[] = $key;
$output[$key] = $val[$key];
}
}
}
print_r($output);
print_r($output); will give you the expected result.

how to flatten a multidimensional array in php [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 1 year ago.
This is my array and i want 60 , 20, 39, 70,12, 29,31,72,59 in a single array. one-dimensional array.
$marks = array(
"abc" => array(
"a" => 60,
"b" => 20,
"c" => 39
),
"def" => array(
"a" => 70,
"b" => 12,
"c" => 29
),
"xyz" => array(
"a" => 31,
"b" => 72,
"c" => 59
)
);
my try was
foreach($marks as $name=>$score)
{
foreach($score as $subject=>$number)
{
$array[]= $number;
}
}
But when i am printing this array it again generate three array.
on print_r($array); its showing this output.
Array ( [0] => 60 [1] => 20 [2] => 39 ) Array ( [0] => 60 [1] => 20 [2] => 39 [3] => 70 [4] => 12 [5] => 29 ) Array ( [0] => 60 [1] => 20 [2] => 39 [3] => 70 [4] => 12 [5] => 29 [6] => 31 [7] => 72 [8] => 59 )
is there any method to get only last array from the above array.or any other solution.
Try this to flatten the array:
<?php
$marks = array(
"abc" => array(
"a" => 60,
"b" => 20,
"c" => 39
),
"def" => array(
"a" => 70,
"b" => 12,
"c" => 29
),
"xyz" => array(
"a" => 31,
"b" => 72,
"c" => 59
)
);
function array_values_recursive($array)
{
$arrayValues = array();
foreach ($array as $value)
{
if (is_scalar($value) OR is_resource($value))
{
$arrayValues[] = $value;
}
elseif (is_array($value))
{
$arrayValues = array_merge($arrayValues, array_values_recursive($value));
}
}
return $arrayValues;
}
var_dump(array_values_recursive($marks));
Output:
array(9) { [0]=> int(60) [1]=> int(20) [2]=> int(39) [3]=> int(70) [4]=> int(12) [5]=> int(29) [6]=> int(31) [7]=> int(72) [8]=> int(59) }
This custom function was taken from: http://php.net/manual/en/function.array-values.php
you can do in either traditional way i.e. foreach loop and also can use iterator. have a look on below solution:
1) using foreach loop and array_merge function
$marks = array(
"abc" => array(
"a" => 60,
"b" => 20,
"c" => 39
),
"def" => array(
"a" => 70,
"b" => 12,
"c" => 29
),
"xyz" => array(
"a" => 31,
"b" => 72,
"c" => 59
)
);
$new_array = array();
foreach ($marks as $mark) {
$new_array = array_merge($new_array, array_values($mark));
}
print_r($new_array);
2) using ArrayIterator:
$new_array = array();
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($marks));
foreach ($iterator as $key => $value) {
$new_array[] = $value;
}
print_r($new_array);
In both solution Output will be:
Array
(
[0] => 60
[1] => 20
[2] => 39
[3] => 70
[4] => 12
[5] => 29
[6] => 31
[7] => 72
[8] => 59
)
Because you're dumping $array inside the first foreach loop :)
Your sound like you may be declare your $array in for loop ,if you do so you will get three arrays.So declare outside of for loop will be get single array
$array = array(); //correct
foreach($marks as $name=>$score)
{
//$array = array(); //incorrect
foreach($score as $subject=>$number)
{
$array[]= $number;
}
}
var_dump($array);
foreach($marks as $name=>$score)
{
foreach($score as $subject=>$number)
{
$array[]= $number;
}
}

Categories