How to merge Arrays in php - php

How to merge many Arrays in php
$array1="Array ( [0] => mouse ) Array ( [0] => mac ) Array ( [0] => keyboard )";
how i can array like this
Array( [0] =>mouse [1] => mac [2] =>keyboard );

depending on how your arrays are being stored, there are a couple of options.
Here are 2 examples:
<?php
$old_array = array(
array('mouse'),
array('mac'),
array('keyboard')
);
$new_array = array();
foreach($old_array as $a){
$new_array[] = $a[0];
}
echo '<pre>',print_r($new_array),'</pre>';
//// OR ////
$array1 = array('mouse');
$array2 = array('mac');
$array3 = array('keyboard');
$new_array = array_merge($array1,$array2,$array3);
echo '<pre>',print_r($new_array),'</pre>';

You should use array_merge function of PHP.
This:
<?php
$a1=array("red","green");
$a2=array("blue","yellow");
print_r(array_merge($a1,$a2));
?>
will return this:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
It's as easy as a piece of cake! :)
Try it: http://www.w3schools.com/php/showphp.asp?filename=demo_func_array_merge
Tutorials:
http://www.w3schools.com/php/func_array_merge.asp
http://php.net/array_merge

So you basically have an array of arrays. You can do this in the following way:
$array = array(array(0 => 'mouse'), array(1 => 'mac'), array(2 => 'keyboard'));
$mergedArray = array();
foreach ($array as $part) {
$mergedArray = array_merge($mergedArray, $part);
}
var_dump($mergedArray);
The result is exactly what you would expect:
array(3) {
[0]=>
string(5) "mouse"
[1]=>
string(3) "mac"
[2]=>
string(8) "keyboard"
}
If you also have scalars in the big array, you can modify the loop to the following:
foreach ($array as $part) {
if (!is_array($part)) {
$mergedArray[] = $part;
} else {
$mergedArray = array_merge($mergedArray, $part);
}
}
Note: This will merge all values from all sub arrays, it's not limited to one entry per sub array.

php array_merge() function, Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
Merge N number of array using $array = array_merge( $array1 , $array2, $array3 ..... $arrayN);
$array1 = array ( '0' => 'mouse' );
$array2 = array ( '0' => 'mac' );
$array3 = array ( '0' => 'keyboard' );
$array = array_merge( $array1 , $array2, $array3);
echo "<pre>";
print_r($array);
echo "</pre>";
O/P:
Array
(
[0] => mouse
[1] => mac
[2] => keyboard
)
More info: http://us2.php.net/array_merge

Related

Remove duplicates from a multi-dimensional array based on 2 values

I have an array that looks like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2"),
array("Will","Smith","4")
);
In the end I want the array to look like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2")
);
The array_unique with the SORT_REGULAR flag checks for all three value. I've seen some solutions on how to remove duplicates based on one value, but I need to compare the first two values for uniqueness.
Simple solution using foreach loop and array_values function:
$arr = array(
array("John","Smith","1"), array("Bob","Barker","2"),
array("Will","Smith","2"), array("Will","Smith","4")
);
$result = [];
foreach ($arr as $v) {
$k = $v[0] . $v[1]; // considering first 2 values as a unique key
if (!isset($result[$k])) $result[$k] = $v;
}
$result = array_values($result);
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => John
[1] => Smith
[2] => 1
)
[1] => Array
(
[0] => Bob
[1] => Barker
[2] => 2
)
[2] => Array
(
[0] => Will
[1] => Smith
[2] => 2
)
)
Sample code with comments:
// array to store already existing values
$existsing = array();
// new array
$filtered = array();
foreach ($array as $item) {
// Unique key
$key = $item[0] . ' ' . $item[1];
// if key doesn't exists - add it and add item to $filtered
if (!isset($existsing[$key])) {
$existsing[$key] = 1;
$filtered[] = $item;
}
}
For fun. This will keep the last occurrence and eliminate the others:
$array = array_combine(array_map(function($v) { return $v[0].$v[1]; }, $array), $array);
Map the array and build a key from the first to entries of the sub array
Use the returned array as keys in the new array and original as the values
If you want to keep the first occurrence then just reverse the array before and after:
$array = array_reverse($array);
$array = array_reverse(array_combine(array_map(function($v) { return $v[0].$v[1]; },
$array), $array));

Combine Indexed arrays with the same keys

I am using the Flot jQuery plugin to create a graph on how many visitors there have been per platform. I would like to create a 4th line with total visitors, calculated by previously retrieved data.
I need to combine several multi-dimensional Indexed arrays, but not simply merging them recursively. I.E:
$arr1 = [[2016/05/04,2],[2016/05/03,4],[2016/05/02,6]];
$arr2 = [[2016/05/04,1],[2016/05/03,3],[2016/05/02,2]];
$arr3 = [[2016/05/04,6],[2016/05/03,7],[2016/05/02,8]];
The output should be:
$arrTotal = [[2016/05/04,9],[2016/05/03,14],[2016/05/02,16]];
How do I accomplish this in a (fairly) simple way?
First of all, you cannot declare your dates the way you did:
$arr1 = [[2016/05/04,2],[2016/05/03,4],[2016/05/02,6]];
Because it's going to take 2016, divide it by 5 then divide it by 4. You need to put them into quotes.
$arr1 = [['2016/05/04',2],['2016/05/03',4],['2016/05/02',6]];
But to create an associative array, you should do it this way:
$arr1 = array('2016/05/04' => 2, '2016/05/03' => 4, '2016/05/02' => 6);
$arr2 = array('2016/05/04' => 1, '2016/05/03' => 3, '2016/05/02' => 2);
$arr3 = array('2016/05/04' => 6, '2016/05/03' => 7, '2016/05/02' => 8);
Now all you want to do, is loop through each array and sum them up.
$merge = array();
function mergeArray(Array &$merge, Array $array){
// Loop through each key and value
foreach($array as $key => $value)
// Make sure the value is numeric
if(is_numeric($value)){
if(!isset($merge[$key]))
$merge[$key] = $value;
else
$merge[$key] += $value;
}
}
mergeArray($merge, $arr1);
mergeArray($merge, $arr2);
mergeArray($merge, $arr3);
And now if you dump the $merge:
array(3) {
["2016/05/04"]=>
int(9)
["2016/05/03"]=>
int(14)
["2016/05/02"]=>
int(16)
}
Build a method that will sum the values by respecting the keys of existing values.
$arr1 = array('2016/05/04'=>2,'2016/05/03'=>4,'2016/05/02'=>6);
$arr2 = array('2016/05/04'=>1,'2016/05/03'=>3,'2016/05/02'=>2);
$arr3 = array('2016/05/04'=>2,'2016/05/03'=>7,'2016/05/02'=>8);
function array_sum(&$new_arr,$arr) {
foreach ($arr as $date_key => $num_value) {
// initialize date in new array with 0, if not done previously
if (! isset($new_arr[$date_key])) { $new_arr[$date_key] = 0; }
// add number for indexed element of array
$new_arr[$date_key] += $num_value;
}
}
$new_arr = array();
array_sum($new_array,$arr1);
array_sum($new_array,$arr2);
array_sum($new_array,$arr3);
You are trying to sum up every second value from each nested array relatively to their position in the parent array.There's a short and simple solution using array_map, array_sum and array_column functions:
$groupped = array_map(null, $arr1,$arr2,$arr3);
$result = array_map(function($v){
return [$v[0][0], array_sum(array_column($v, 1))];
}, $groupped);
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => 2016/05/04
[1] => 9
)
[1] => Array
(
[0] => 2016/05/03
[1] => 14
)
[2] => Array
(
[0] => 2016/05/02
[1] => 16
)
)

Reverse array elements with specific value

I have an array like this
$array = array( [0] => 'red1', [1] => 'blue1', [2] => 'red2', [3] => 'red3', [4] => 'blue2' );
A want to reverse order of elements with red value only so it looks like this:
$array = array( [0] => 'red3', [1] => 'blue1', [2] => 'red2', [3] => 'red1', [4] => 'blue2' );
I think a possible solution might be to:
Get all the values from the $array that you are looking for and
store them in an array $found
Reverse the values in $found keeping the keys
Replace the values in $array with the values from $found using
the key
For example:
$array = array(0 => 'red1', 1 => 'blue1', 2 => 'red2', 3 => 'red3', 4 => 'blue2');
// First get all the values with 'red' and store them in an array
$found = preg_grep('/red\d+/', $array);
// Reverse the values, keeping the keys
$found = array_combine(
array_keys($found),
array_reverse(
array_values($found)
)
);
// Then replace the values of $array with values having the same keys in $found
$array = array_replace($array, $found);
var_dump($array);
Will result in:
array(5) {
[0]=>
string(4) "red3"
[1]=>
string(5) "blue1"
[2]=>
string(4) "red2"
[3]=>
string(4) "red1"
[4]=>
string(5) "blue2"
}
You can catch red's quote to a new array and sort them.
<?php
$arr = array(
'red1',
'blue1',
'red2',
'red3',
'blue2'
);
$sortArr = array();
for ($i=0; $i < sizeof($arr); $i++) {
if(strstr($arr[$i], "red")){
$sortArr[] = &$arr[$i];
}
}
?>
I think you can do using searching specific words by strpos and sorting array by ksort (sort associative arrays in ascending order, according to the key)
foreach ($array as $key => $value) {
if(strpos($value,"red") !== false){
($key === 0) ? $index = 3 : (($key === 3) ? $index = 0 : $index = 2);
$temp[$index] = $value;
}
else {
$temp[$key] = $value;
}
}
ksort($temp);
var_dump($temp);
[But It will not work in larger array than this]

How to replace array keys with another array values

I have two arrays and I want to replace the second array keys with the first array values if both keys matches.
As an example: Replace A with Code And B with name
How to do this;
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
foreach($replacement_keys as $key => $value){
foreach($value as $sk => $sv){
foreach($array as $rk => $rv){
if($sk == $rk ){
$sk = $rv;
}
}
}
}
echo "<pre>";
print_r($value);
echo "</pre>";
exit;
I want the result to be like this
array(
[0] => Array
(
[name] => ahmed
[code] => 1020
)
[1] => Array
(
[name] => sara
[code] => 2020
)
)
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
foreach($replacement_keys as &$value)
{
foreach ($array as $key => $name) {
$value[$name] = $value[$key];
unset($value[$key]);
}
}
var_dump($replacement_keys);
Try this:
<?php
$array = array('A' => 'code', 'B' =>'name');
$replacement_keys = array
(
array("A"=>'sara','B'=>2020),
array("A"=>'ahmed','B'=>1010)
);
$newArray = array();
foreach($replacement_keys as $key => $value)
{
foreach($value as $key2 => $value2)
{
if(isset($array[$key2]))
{
$newArray[$key][$array[$key2]] = $value2;
}
else
{
$newArray[$key][$key2] = $value2;
}
}
}
print_R($newArray);
This should work for you, nice and simple (I'm going to assume that A should be name and B should be code):
(Here I go through each array from $replacement_keys with array_map() and replace the array_keys() with the array_values() of $array. Then I simply get all array values from $replacement_keys and finally I array_combine() the replaced array keys with the corresponding array values)
$result = array_map("array_combine",
array_map(function($v)use($array){
return str_replace(array_keys($array), array_values($array), array_keys($v));
}, $replacement_keys),
$replacement_keys
);
output:
Array ( [0] => Array ( [code] => sara [name] => 2020 ) [1] => Array ( [code] => ahmed [name] => 1010 ) )
array_fill_keys
(PHP 5 >= 5.2.0, PHP 7)
array_fill_keys — Fill an array with values, specifying keys
Description
array array_fill_keys ( array $keys , mixed $value )
Fills an array with the value of the value parameter, using the values of the keys array as keys.
http://php.net/manual/en/function.array-fill-keys.php

PHP intersect of array of array

I have an array of array .
Example like
a[0]={1,2,3};
a[1]={2,3,4};
**Edit** in a[2] from a[2]={4,5};
a[2]={2,4,5};
and more
How can I find common element which exist in all array ?
This is a function I have made. It's just a reference for a multidimensional array.
<?php
$array1 = array('angka'=>12,'satu','2'=>'dua','tiga'=>array('dua','enam','empat'=>array('satu','lima',12)));//object
$array2 = array('dua','tiga','empat',12);//object as intersect refference
function intersect($data=NULL)
{
if(!empty($data))
{
$crashed = array();
$crashed2 = array();
foreach($data[0] as $key=>$val)
{
if(!is_array($val))
{
$crashed[$key] = in_array($val,$data[1]);//return true if crashed (intersect)
}
else
{
$crashed2[$key] = intersect(array($val,$data[1]));
}
$crashed = array_merge($crashed,$crashed2);
}
}
return $crashed;
}
$intersect = intersect(array($array1,$array2));
print_r($intersect);
?>
It returns a result like this:
Array ( [angka] => 1 [0] => [1] => 1 [tiga] => Array ( [0] => 1 [1] => [empat] => Array ( [0] => [1] => [2] => 1 ) ) )
It returns true if the value of an array matches with a reference array.
Hope the code can help you.
Have a look here array-intersect.
You could use it like this:
$intersect = $a[0];
for ($i = 1; $i < count($a); $i++)
{
$intersect = array_intersect($intersect, $a[$i]);
}
You can avoid foreach loop by
call_user_func_array('array_intersect',$a);
As the name suggest, I think you can just use array-intersect
From that page:
<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>
gives
Array
(
[a] => green
[0] => red
)

Categories