Merge two indexed arrays of indexed arrays based on first column value - php

I have two arrays like this:
$array1 = [
[10, 'Some Name..'],
[11, 'Some Name..'],
[13, 'Some Name..'],
];
$array2 = [
[13, 'Viewed']
];
How can I merge these two arrays without looping? Is there any php functionality available for this? I need this kind of output:
[
[10, 'Some Name..'],
[11, 'Some Name..'],
[13, 'Some Name..', 'Viewed']
]

You can use the PHP function array_merge_recursive.
See the example:
<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

There will not be a non-loop way to accomplish this. Maybe you are seeking function-based syntax, but for this scenario I think this will only introduce unnecessary convolution.
For best efficiency, generate a result array that doubles as a lookup array. If the key already exists in the result array, you only need to push the [1] value into that row. If you wish to reindex the result, just call array_values() on it.
Code: (Demo)
$array1 = [
[10, 'Some Name..'],
[11, 'Some Name..'],
[13, 'Some Name..'],
];
$array2 = [
[13, 'Viewed']
];
$result = [];
foreach (array_merge($array1, $array2) as $row) {
if (!isset($result[$row[0]])) {
$result[$row[0]] = $row;
} else {
$result[$row[0]][] = $row[1];
}
}
var_export($result);
Functional style: (Demo)
var_export(
array_reduce(
array_merge($array1, $array2),
function($result, $row) {
if (!isset($result[$row[0]])) {
$result[$row[0]] = $row;
} else {
$result[$row[0]][] = $row[1];
}
return $result;
}
)
);

Related

How to get max element at each index while comparing two arrays?

I have two indexed arrays of identical length:
$first_array = [1,3,4,5,6];
$second_array = [5,2,1,7,9];
I need to generate a new array that consists of the higher value between the two elements at each index.
The output should be:
$output_array[5, 3, 4, 7, 9];
Super easy one-liner:
Pass both arrays to array_map(), as it synchronously loops through both sets of data, call max() on the two elements.
Code: (Demo)
$first_array = [1, 3, 4, 5, 6];
$second_array = [5, 2, 1, 7, 9];
var_export(array_map('max', $first_array, $second_array));
Output:
array (
0 => 5,
1 => 3,
2 => 4,
3 => 7,
4 => 9,
)
Try this way. demo
<?php
$first_array = array(1,3,4,5,6);
$second_array = array(5,2,1,7,9);
$return = array();
foreach($first_array as $key => $value){
if($first_array[$key] > $second_array[$key]){
$return[] = $first_array[$key];
}else{
$return[] = $second_array[$key];
}
}
print_r($return);

Combine array and add key for each array

I just can't find the right question for this
pretty much merging array From this
$arr1 = ["temp1", "temp2", "temp3"];
$arr2 = [5, 7, 2];
to this
$combined = [["name" => "temp1", "number" => 5], ["name" => "temp2", "number" => 7], ["name" => "temp3", "number" => 2]];
any idea to do it in most efficient way other than foreach?
$arr1 = ["temp1", "temp2", "temp3"];
$arr2 = [5, 7, 2];
foreach($arr1 as $key => $value)
{
$r[$key]['name'] = $value;
$r[$key]['number'] = $arr2[$key];
}
print_r($r);
Built-in function array_map actually can work with multiple arrays:
$result = array_map(function($value1, $value2) {
return ["name" => $value1, "number" => $value2];
}, $arr1, $arr2);
Here are some benchmarks comparing with simple foreach
You can use a foreach loop,
$result = [];
foreach($arr1 as $key => $value){
$resutl[] = array("name"=>$value,"number"=>$arr2[$key]);
}
You can do the following code to get your result
$arr1 = ["temp1", "temp2", "temp3"];
$arr2 = [5, 7, 2];
$count = count($arr1);
$combined = array();
for($i=0;$i<$count;$i++){
$combined[$i]['name'] = $arr1[$i];
$combined[$i]['number'] = $arr2[$i];
}

How to merge arrays in PHP with a same value

I want to merge two arrays with the same value -> user_id to one array.
You can see I have two arrays with different objects. I want merge them by user_id to one array with all objects.
For example:
$array1 = [
$array[0]->leads = 5643;
$array[0]->user_id= 15;
$array[0]->sales = 1433;
$array[1]->leads = 3264;
$array[1]->user_id= 9;
$array[1]->sales = 1254;
];
$array2 = [
$array[0]->user_id= 15;
$array[0]->processing = 2300;
$array[0]->deleted = 203;
$array[1]->user_id= 9;
$array[1]->processing = 103;
$array[1]->deleted = 80;
];
The following array is the target.
$result = [
$array[0]->user_id= 15;
$array[0]->processing = 2300;
$array[0]->leads = 5643;
$array[0]->deleted = 203;
$array[0]->sales = 1433;
$array[1]->user_id= 9;
$array[1]->processing = 103;
$array[1]->leads = 3264;
$array[1]->deleted = 80;
$array[1]->sales = 1254;
];
Iterate your array and build the combined array of objects using user_id as the key.
foreach ($array as $entry) {
// if an entry for this user id hasn't been created in the result, add this object
if (!isset($result[$entry->user_id])) {
$result[$entry->user_id] = $entry;
// otherwise, iterate this object and add the values of its keys to the existing entry
} else {
foreach ($entry as $key => $value) {
$result[$entry->user_id]->$key = $value;
}
}
}
Given the additional info you just gave (two separate arrays) the solution is basically the same, just merge the two arrays together first.
foreach (array_merge($array1, $array2) as $entry) { ...
(Working example at https://3v4l.org/ccdQc)
How about array_merge,
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
or array_merge_recursive,
<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>
Example
$array = [
1 => [
'cost' => '25'
],
2 => [
'blah' => 'test'
]
];
$new_array = array_merge_recursive($array[1], $array[2]);
var_dump($new_array);
Output
array(2) {
["cost"]=>
string(2) "25"
["blah"]=>
string(4) "test"
}
Live Example
Repl
<?php
$array1= array("leads"=> 5643,"user_id"=>15,"sales" =>1433);
$array2= array("user_id"=> 15,"processing" => 2300,"deleted" => 203);
$array= (array_merge($array1,$array2));
print_r($array);
?>

Pushing multiple arrays to slice into one || PHP

So I have something like:
$array = array("red", "yellow", "hello", "world");
$array2 = array("1", "2", "3", "4");
$myArray = array();
array_push($myArray, $array, $array2 );
$myArray = array_slice($myArray, 0, 2);
and I want $myArray to be ["red", "yellow"], and if $array was empty $myArray would be ["1", "2"]
Does that make any sense? Right now array_slice is counting the arrays being pushed into $myArray, not the content inside them. How would I go about doing this?
Where you use array_push you probably want to use array_merge:
$array = array("red", "yellow", "hello", "world");
$array2 = array("1", "2", "3", "4");
$myArray = array_merge($array, $array2);
$myArray = array_slice($myArray, 0, 2);
Explanation:
array_push pushes the elements to the end of the existing array, so
$array = array('a');
array_push($array, 'b');
// results in $array = array('a', 'b');
Thus in your code, just after the array_push-call
$myArray = array(array('red', 'yellow', ...), array('1', '2', ...))
array_merge merges two or more arrays
$myArray = array_merge($array, $array2);
// results in $myArray = array('red', 'yellow', ..., '1', '2', ...)
Try using array_merge() instead of array_push()
$array = array("red", "yellow", "hello", "world");
$array2 = array("1", "2", "3", "4");
$myArray = array_merge($array, $array2 );
$myArray = array_slice($myArray, 0, 2);
array_push() is adding each array as an element of $myArray instead of combining them with it.

I want to compare two arrays in PHP

Assume that I have two arrays as follow:
$array1 = array(1, 3, 5);
$array2 = array('x'=> 1, 'y'=> 2, 'z'=> 5);
How to check that the two arrays are exactly the same in most efficient and proper way and it doesn't care the keynames of the *$array2.
I want to make a function which should return true if values are exactly the same, and false if any of the ones are different both in value(s) and number of elements.
Thanks for your time and reading.
In the simplest case you can just use array_diff. It ignores the keys in your second array, but also the order of the values. It would return an empty set if the arrays are equal:
if (count(array_diff($array1, $array2)) == 0) {
// equal
You could also compare the arrays directly, after stripping keys from the second:
if ($array1 == array_values($array2)) {
That would additionally compare the order of contained values.
array_values($array1) === array_values($array2)
Assuming that arrays have same order.
Try this
$array1 = array(1, 3, 5);
$array2 = array('x'=> 1, 'y'=> 2, 'z'=> 5);
$array2 = array_values($array2);
echo $array1 == $array2 ? 'true' : 'false';
array_diff will do the job for you:
<?php
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
if(empty($result)){
// arrays contain the same values!
}
?>
Create a class containing an array and make that class implement the Comparable interface, for example http://php.net/manual/language.oop5.interfaces.php#69467
like this:
<?php
$array1 = array ("a" => "green", "b" => "brown", "c" => "blue", "red");
$array2 = array ("a" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
if(count($result) == 0)
{
.......
}
?>

Categories