How to add multiple arrays to a subarray? - php

I have the following three arrays of objects:
First Array: $array1
Array (
[0] => Array (
[id] => 1
[name] => world
)
)
Second Array: $array2
Array (
[count] => 1
)
Third Array: $array3
Array (
[KM] => 2
)
I want to add the associative elements from $array2 and $array3 into the subarray at $array1[0].
Desired output:
Array (
[0] => Array
(
[id] => 1
[name] => world
[count] => 1
[KM] => 2
)
)

This is how you would use array_merge()
<?php
$array1 = array(array("id" => 1, "name" => "world"));
$array2 = array("KM" => 2);
$array3 = array("count" => 1);
print_r(array(array_merge($array1[0], $array2, $array3)));
?>
Which would output:
Array
(
[0] => Array
(
[id] => 1
[name] => world
[KM] => 2
[count] => 1
)
)

array_merge is the function you've been looking for
Sample code:
$output_array[0] = array_merge($array1[0], $array2, $array3));
print_r($output_array);

This will get you the desired output:
<?php
$array1 = array(array("id" => 1, "name" => "world"));
$array2 = array("KM" => 2);
$array3 = array("count" => 1);
$array1[0] = array_merge($array1[0], $array2, $array3);
print_r($array1);
?>

array_merge() will merge arrays. Problem is, the structure of your $array1 differs from the others. You have an array inside an array. To produce the desired output as specified you would need this:
$array4 = array(
0 => array_merge($array1[0], $array2, $array3)
);
But I believe you want something more like this:
$array4 = array_merge($array1[0], $array2, $array3);

array array_merge ( array $array1 [, array $... ] )
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.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

Related

Array merge with same keys

I have these three arrays:
Array
(
[1] => sadsad#fsdf.fgh
[2] => rtt#RERT.FDG
[3] => WQEWQ#fgdg.h
)
Array
(
[1] =>
[2] => 4234235
[3] =>
)
Array
(
[2] => 1
)
And I want to generate this output:
Array
(
[1] => array(
[0] => sadsad#fsdf.fgh
)
[2] => array(
[0] => rtt#RERT.FDG
[1] => 4234235
[2] => 1
)
[3] => array(
[0] => WQEWQ#fgdg.h
)
)
I need some assistance because I already researched array_merge_recursive() and array_merge(), but I can't get the correct result.
If I need to use foreach() what must I do to merge these 3 arrays.
Wrote a little script:
$a = array
(
1=>"sadsad#fsdf.fgh",
2=>"rtt#RERT.FDG",
3=>"WQEWQ#fgdg.h",
);
$b = array
(
2 => 4234235
);
$c = array
(
2 => 1
);
$arrayKeys = array_unique(
array_merge(
array_keys($a),
array_keys($b),
array_keys($c)
)
);
$d = array_combine(
$arrayKeys,
array_fill(
0,
count($arrayKeys),
array()
)
);
foreach($a as $key => $value) {
if(!empty($a[$key])) {
$d[$key][] = $a[$key];
}
if(!empty($b[$key])) {
$d[$key][] = $b[$key];
}
if(!empty($c[$key])) {
$d[$key][] = $c[$key];
}
}
var_dump($d);
Also if you want to you can merge together the arrays using the variable names only
//names of the variables to merge together
$arrayVariableNames = array("a","b","c");
//merging array keys together
$arrayKeys = array();
foreach($arrayVariableNames as $variableName) {
$arrayKeys = array_merge(
$arrayKeys,
array_keys(${$variableName})
);
}
$arrayKeys = array_unique($arrayKeys);
//initialize the result array with empty arrays
$resultArray = array_combine(
$arrayKeys,
array_fill(
0,
count($arrayKeys),
array()
)
);
//loop through all the keys and add the elements from all the arrays
foreach($resultArray as $key => &$value) {
foreach($arrayVariableNames as $variableName) {
if(!empty(${$variableName}[$key])) {
$value[] = ${$variableName}[$key];
}
}
}
As you have no doubt discovered, array_merge_recursive() stubbornly smashes all numeric or "numeric string" keys into a 1-dimensional array. To avoid this behavior, you need to cast each of your arrays' initial keys as strings in a way that will not be assumed to be a number by array_merge_recursive().
Additionally you want to filter out all elements that have empty values.
I initially wrote a one-liner that performed the key re-casting then filtered the values, but it is less efficient that way. For your case, you should only use array_filter() on arrays that may possibly contain empty values.
Input Arrays:
$a=[1=>"sadsad#fsdf.fgh",2=>"rtt#RERT.FDG",3=>"WQEWQ#fgdg.h"];
$b=[1=>"",2=>"4234235",3=>""];
$c=[2=>1];
Code:
// remove empty values from all arrays that may have them
$b=array_filter($b,'strlen');
// for all arrays, cast numeric keys to string by prepending with a space
function addK($v){return " $v";}
$a=array_combine(array_map('addK',array_keys($a)),$a);
$b=array_combine(array_map('addK',array_keys($b)),$b);
$c=array_combine(array_map('addK',array_keys($c)),$c);
// merge arrays recursively
$merged=array_merge_recursive($a,$b,$c);
// cast keys back to numeric
$merged=array_combine(array_map('trim',array_keys($merged)),$merged);
// force all top-level elements to be arrays
foreach($merged as $k=>$v){
if(is_string($merged[$k])){$merged[$k]=[$v];}
}
var_export($merged);
Output:
array (
1 => array (
0 => 'sadsad#fsdf.fgh',
),
2 => array (
0 => 'rtt#RERT.FDG',
1 => '4234235',
2 => 1,
),
3 => array (
0 => 'WQEWQ#fgdg.h',
),
)
For readers who want to know the difference when array_merge_recursive() is run with no preparation:
array (
0 => 'sadsad#fsdf.fgh',
1 => 'rtt#RERT.FDG',
2 => 'WQEWQ#fgdg.h',
3 => '',
4 => '4234235',
5 => '',
6 => 1,
)
Notice the 1d array and the re-indexed keys? ...totally useless for the OP.
Finally, for anyone who wants to re-cast the keys to all arrays and would like to make my process more DRY, there may be an opportunity to set up a variadic function or similar. I merely didn't bother to pursue the notion because I didn't want to make my answer anymore complex and it is not a terrible amount of Repeating Myself.

Merger Array Table

I have two array, I would like to merge them without duplicating in "name",
$array1[]= array(name['udi','ari'],id['1','2'])
$array2[]= array(name['udi','ari'],age['22','18'])
result
$arrayresult[]= array(name['udi','ari'],id['1','2'],age['22','18'])
Just simply use array_merge for merging both array as:
Example:
<?php
$array1 = array(
'name'=>array('udi','ari'),
'id'=>array('1','2'),
);
$array2 = array(
'name'=>array('udi','ari'),
'age'=>array('22','18'),
);
$newArr = array_merge($array1,$array2);
echo "<pre>";
print_r($newArr);
?>
Result:
Array
(
[name] => Array
(
[0] => udi
[1] => ari
)
[id] => Array
(
[0] => 1
[1] => 2
)
[age] => Array
(
[0] => 22
[1] => 18
)
)
You can use first $result=array_merge($array1,$array2) and then use $result=array_unique($result) its remove duplicate value.
I think what you're looking for is array_merge:
http://php.net/manual/en/function.array-merge.php
$arrayresult = array_merge($array1,$array2);
should give you:
$arrayresult = array(name('udi','ari'),id('1','2'),age('22','18'))

Merging two assosiative arrays in php?

I have two associative arrays.
array ( [apple]=>1 [banana]=>2 cocunet => 3)
and other array is
array ( [apple]=>2 [banana]=>3 cocunet => 4)
now i want to merge my array like that
array ( [apple]=>1,2 [banana]=>2,3 cocunet => 3,4)
There is no such array in PHP. The thing you want can only be done by creating multidimentional arrays.
$a1 = array( 'apple'=>1,'banana'=>2,'coconut'=> 3);
$a2 = array( 'apple'=>2,'banana'=>3,'coconut'=> 4);
echo "<pre>";
print_r(array_merge_recursive($a1,$a2));
echo "</pre>";
For this you can use the array_merge_recursive() function.
PHPFiddle: http://3v4l.org/5OCKI
If you want the result to be a string then this should work:
foreach( $array_1 as $fruit => $num) {
if(array_key_exists($fruit, $array_2)){ //check if key from array_1 exists in array_2
$final_array[] = array($fruit => $array_1[$fruit].','.$array_2[$fruit]); //concatenate values from shared key
}
}
print_r($final_array) will return:
Array
(
[0] => Array
(
[apple] => 1,2
)
[1] => Array
(
[banana] => 2,3
)
[2] => Array
(
[coconut] => 3,4
)
)
<?php
$array1 = array("apple" => 5, "banana" => 1);
$array2 = array("banana" => 4, "coconut" => 6);
print_r( array_merge_recursive( $array1, $array2 ) );
?>
Returns:
Array ( [apple] => 5 [banana] => Array ( [0] => 1 [1] => 4 ) [coconut] => 6 )
I only used two elements in each of the primary arrays to demonstrate the output prior to having any groups existing, i.e. non-array value.

How can I group arrays into one array in php?

I would like to convert / form the following arrays as example:
Array ( [product_category] => for-women ) Array ( [brand] => 7-diamonds ) Array ( [size] => 12 ) Array ( [color] => 882536 )
Into one array that just merges each array pair and put them altogether :
Array ( [product_category] => for-women [brand] => 7-diamonds [size] => 12 [color] => 882536 )
I tried array_merge and it didn't work. The array out put in my code is from $_SESSION which returns an array (a pair key=> value) like this:
foreach($_SESSION as $k => $v) {
if (strstr($k, 'saved_query_') == true) {
$saved = array_merge($v);
}
}
So I get each array by looping through session which has a query, the result is array pair, I want to combine all pairs found (Do not know how to use array_merge in that case).
I tried array_combine and array_merge they do not seem like the functions I need based on php manual:
array_combine — Creates an array by using one array for keys and another for its values
Which I do not want to do, I just want to copy/move small arrays in one array, without changing any pairing/key/value.
You can try using array_merge
$array0 = Array ( "product_category" => "for-women" );
$array1 = Array ( "brand" => "7-diamonds" ) ;
$array2 = Array ( "size" => "12" ) ;
$array3 = Array ( "color" => "882536" );
$array = array_merge($array0,$array1,$array2,$array3);
print_r($array);
Output
Array ( [product_category] => for-women [brand] => 7-diamonds [size] => 12 [color] => 882536 )
See Demo
* ----- Update ----- *
If you are looking through a session
$_SESSION = Array();
$_SESSION[0] = Array("product_category" => "for-women");
$_SESSION[1] = Array("brand" => "7-diamonds");
$_SESSION[2] = Array("size" => "12");
$_SESSION[3] = Array("color" => "882536");
$final = array();
foreach ( $_SESSION as $key => $value ) {
$final = array_merge($final, $value);
}
print_r($final);
Use array_merge_recursive() :
$result = array_merge_recursive($ar1, $ar2 [, array $...]);
Example: http://codepad.viper-7.com/Yr0LTb
Use array_merge instead.
$ret = array_merge($arr1, $arr2, $arr3);
With your code, you should do:
$saved = array_merge($saved, $v);
You should have a look at the array_merge() function in PHP: http://php.net/manual/en/function.array-merge.php
Simply use as follows:
$array1 = Array ( [product_category] => for-women );
$array2 = Array ( [brand] => 7-diamonds );
$array3 = Array ( [size] => 12 );
$array4 = Array ( [color] => 882536 );
$combined = array_merge($array1, $array2, $array3, $array4);

Two array with same index key and structure need single array of combine array of it

My First Array Look Like This
$array1 = array('0' => 'news', '1' => 'game');
Array
(
[0] => news
[1] => game
)
My Second Array Look Like This
$array2 = array('0' => '1', '1' => '2');
Array
(
[0] => 1
[1] => 2
)
I Need Output Like This
$array3 = array(array('0'=>'new', '1'=>'1'),array('0'=>'game', '1'=>'2'));
Array
(
[0] => Array
(
[0] => new
[1] => 1
)
[1] => Array
(
[0] => game
[1] => 2
)
)
I tried multiple way using array_merge, array_merge_recursive and loop
but not getting the proper output.
Here's an easy way:
$result = array_map(null, $array1, $array2);
This will work regardless of the indexes, so in your case, for better or worse, these would also produce the same result:
$array1 = array(1 => 'news', 5 => 'game');
$array2 = array(2 => '1', 6 => '2');
You can use array_map for this, with null as first argument:
$result = array_map(null, $first_array, $second_array);
use this code
$array1 = array_values($array1);
$array2 = array_values($array2);
$array = [];
$count = count($array1);
for($i=0;$i<$count;$i++)
$array[] = [$array1[$i] , $array2[$i]];
var_dump($array);
Lot's of ways to do this, array_map as other's have answered is probably your best bet. IF you want to see what's happening:
foreach($array1 as $key => $value){
$array3[$key] = array($value, $array2[$key]);
}

Categories