Merging and combining arrays in PHP - php

I have multiple associative arrays, similar to the following:
$arr1 = array(0 => 12, 5 => 10, 19 => 48);
$arr2 = array(0 => 14, 7 => 9, 12 => 11, 19 => 30);
I would like to merge these arrays so that I have a single set of keys (0, 5, 7, 12, 19) and each points to an array with the values from the original arrays, and null if the value doesn't exist in the original array:
$merge = array(
0 => array(12, 14),
5 => array(10, null),
7 => array(null, 9),
12 => array(null, 11),
19 => array(48, 30)
);
I need to be able to do this for an arbitrary number of arrays. I'm not sure where to start with this.
I could, I suppose, iterate through each array, append it's value to the result - but I'd have to check to see if I have the requisite number of elements in each resulting array before appending the current value to that index - which isn't terribly efficient.
Ideas or pointers?

$arr1 = array(0 => 12, 5 => 10, 19 => 48);
$arr2 = array(0 => 14, 7 => 9, 12 => 11, 19 => 30);
$keys = array_merge(array_keys($arr1), array_keys($arr2));
$merged = array();
foreach ($keys as $key) {
$merged[$key] = array();
$merged[$key][] = isset($arr1[$key]) ? $arr1[$key] : null;
$merged[$key][] = isset($arr2[$key]) ? $arr2[$key] : null;
}
ksort($merged);
echo '<pre>', var_dump($merged), '</pre>';
modified for an arbitrary number of arrays
$arrays = array(
array(0 => 12, 5 => 10, 19 => 48),
array(0 => 14, 7 => 9, 12 => 11, 19 => 30),
// ... more arrays
);
$keys = array();
foreach ($arrays as $arr) {
$keys = array_merge($keys, array_keys($arr));
}
$merged = array();
foreach ($keys as $key) {
$merged[$key] = array();
foreach ($arrays as $arr) {
$merged[$key][] = isset($arr[$key]) ? $arr[$key] : null;
}
}
ksort($merged);
echo '<pre>', var_dump($merged), '</pre>';

EDIT
<?php
$arr1 = array(0 => 12, 5 => 10, 19 => 48);
$arr2 = array(0 => 14, 7 => 9, 12 => 11, 19 => 30);
foreach($arr1 as $k => $v){
if(array_key_exists($k, $arr2)){
$newarr[$k][] = $v;
$newarr[$k][] = $arr2[$k];
}else{
$newarr[$k][] = $v;
$newarr[$k][] = 'NULL';
}
}
foreach($arr2 as $k => $v){
if(!array_key_exists($k, $arr1)){
$newarr[$k][] = 'NULL';
$newarr[$k][] = $v;
}
}
ksort($newarr);
echo '<pre>';
print_r($newarr);
?>
Output:
Array
(
[0] => Array
(
[0] => 12
[1] => 14
)
[5] => Array
(
[0] => 10
[1] => NULL
)
[7] => Array
(
[0] => NULL
[1] => 9
)
[12] => Array
(
[0] => NULL
[1] => 11
)
[19] => Array
(
[0] => 48
[1] => 30
)
)

I think this is what you're looking for.
/*Merge function*/
function merge($a1, $a2)
{
foreach($a1 as $key => $val)
$a1[$key] = Array($a1[$key], null);
foreach($a2 as $key => $val)
$a1[$key] = Array((isset($a1[$key]))? $a1[$key][0]: null, $val);
return ksort($a1);
}
/*Test*/
$arr1 = array(0 => 12, 5 => 10, 19 => 48);
$arr2 = array(0 => 14, 7 => 9, 12 => 11, 19 => 30);
foreach(merge($arr1, $arr2) as $key => $val){
echo "<br />$key --";
print_r($val);
}
/*output*/
0 --Array ( [0] => 12 [1] => 14 )
5 --Array ( [0] => 10 [1] => )
7 --Array ( [0] => [1] => 9 )
12 --Array ( [0] => [1] => 11 )
19 --Array ( [0] => 48 [1] => 30 )

Try this function:
function multimerge ($array1, $array2) {
if (is_array($array2) && count($array2)) {
foreach ($array2 as $k => $v) {
if (is_array($v) && count($v)) {
$array1[$k] = multimerge($array1[$k], $v);
} else {
$array1[$k] = $v;
}
}
} else {
$array1 = $array2;
}
return $array1;
}
http://php.net/manual/en/function.array-merge.php

Related

Loop a array and create new array by combine two array

$array1=Array("2016-11-02","2016-11-03","2016-11-04","2016-11-05","2016-11-06","2016-11-07","2016-11-08");
$array2 = Array([0] => Array("count" => 2 ,"created_at"=> 2016-11-04));
//desired result will
$array3 = Array(
[0] => Array("count" => 0 ,"created_at" => 2016-11-02),
[1] => Array("count" =>0 "created_at" => 2016-11-03),
[2] => Array("count" => 2 ,"created_at" => 2016-11-04),
[3] => Array("count" => 0 ,"created_at" => 2016-11-05),
[4] => Array("count" =>0 ,"created_at" => 2016-11-06),
[5] => Array("count" => 0 ,"created_at" => 2016-11-07),
[6] => Array("count" => 0 ,"created_at" => 2016-11-08)
);
Try this -
foreach ($array1 as $date) {
//if value resides in $array2 - use that count
if (in_array($date, $array2[0])) {
$array3[]['count'] = $array2[0]['count'];
}
else {
$array3[]['count'] = 0;
}
$array3[]['created_at'] = $date;
}
print_r($array3); //should be your required array.
$array1=array("2016-11-02","2016-11-03","2016-11-04","2016-11-05","2016-11-06","2016-11-07","2016-11-08");
$array4 = array(0 => array("count" =>'2' ,"created_at"=>'2016-11-04'),1 => array("count" =>'2' ,"created_at"=>'2016-11-05'));
$array3 = array();
for($i =0;$i<count($array1); $i++) {
$array3[$i]['count'] = 0;
$array3[$i]['created_at'] = $array1[$i];
}
$arr = array_merge($array3,$array4);
foreach($arr as $k => $v) {
foreach($arr as $key => $value) {
if($k != $key && $v['created_at'] == $value['created_at']) {
unset($arr[$k]);
}
}
}
$arr = array_values($arr);
function date_compare($a, $b) {
$t1 = strtotime($a['created_at']);
$t2 = strtotime($b['created_at']);
return $t1 - $t2;
}
usort($arr, 'date_compare');
print_r($arr);

How to concatenate two or more arrays in PHP without loosing values if it is same key and different values

I have two multi-dimensional arrays. I need to concatenate the two without loosing any values which have the same key and different values. Here is the scenario:
Array1
(
[0] => 11
[2] => 12
[3] => 13
[4] => (
[0] => 100
[1] => 200
)
[5] => 2
[6] => 3
)
Array2
(
[0] => 11
[2] => 12
[3] => 13
[4] => (
[0] => 400
[1] => 500
)
[5] => 2
[6] => 3
)
The result should be
Result
(
[0] => 11
[2] => 12
[3] => 13
[4] => (
[0] => (
[0] => 100
[1] => 400
)
[1] => (
[0] => 200
[1] => 500
)
)
[5] => 2
[6] => 3
)
Here is one solution:
<?php
$arrayA = array(0 => 11, 2 => 12, 3 => 13, 4 => array(0 => 100, 1 => array(0 => 222),), 5 => 2, 6 => 3);
$arrayB = array(
0 => 11,
2 => 12,
3 => 13,
4 => array(
0 => 100,
1 => array(0 => array(0 => 'test1', 1 => 'test2'), 1 => array(0 => 'test1', 1 => 'test2'),),
),
5 => 2,
6 => 3
);
/**
* #param $a
* #param $b
* #return array
*/
function array_merge_graceful($a, $b)
{
$c = [];
if (is_array($a) && is_array($b)) {
foreach (array_merge(array_keys($a),array_keys($b)) as $i) {
if (!array_key_exists($i, $a)) {
$c[$i] = $b[$i];
} elseif (!array_key_exists($i, $b)) {
$c[$i] = $a[$i];
} else {
$c[$i] = array_merge_graceful($a[$i], $b[$i]);
}
}
} else {
if ($a <> $b) {
$c = [$a, $b];
} else {
$c = $a;
}
}
return $c;
}
var_dump(array_merge_graceful($arrayA, $arrayB));
?>
Try something like this
<?php
$array1 = array(11, 12, 13, array(100, 200), 2, 3);
$array2 = array(11, 12, 13, array(400, 500), 2, 3);
echo "<pre>";
print_r($array1);
print_r($array2);
$combine = array();
foreach ($array1 as $key => $value) {
if (array_key_exists($key, $combine)) {
//if is array
if (is_array($combine[$key])) {
$combine[$key] = array($combine[$key], $value);
}
} else {
$combine[$key] = $value;
}
}
foreach ($array2 as $key => $value) {
if (array_key_exists($key, $combine)) {
//if is array
if (is_array($combine[$key])) {
$combine[$key] = array($combine[$key], $value);
}
} else {
$combine[$key] = $value;
}
}
echo "<hr>";
print_r($combine);
use array_merge_recursive() function for merging arrays.For more details please refer http://php.net/manual/en/function.array-merge-recursive.php

Move inner array values to parent array, reset keys and change key name to string

I have an array as such:
[0] => Array
(
[0] => 1
[1] => 30
[2] => 33
)
[1] => Array
(
[id] => 5
)
I want to move all values in the [0] index out so they become part of the parent array. So the final outcome would look like such:
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 30
)
[2] => Array
(
[id] => 33
)
[3] => Array
(
[id] => 5
)
As you can see the numerical indexes on [0] have now changed to id
I've tried using array_map('current', $array[0])
to no avail, any suggestions?
You could use the ol' trusty double foreach:
$new_array = array();
foreach ($array as $arr) {
foreach ($arr as $ar) {
$new_array[] = array('id'=>$ar);
}
}
Demo
$data = array(
array(1, 30, 33),
array('id' => 5)
);
$result = array();
array_walk_recursive(
$data,
function($value) use (&$result) {
$result[] = array('id' => $value);
}
);
var_dump($result);
Just to show that iterators can be really useful tools as well:
$data = array(
array(1, 30, 33),
array('id' => 5)
);
$result = array();
foreach (new RecursiveIteratorIterator(
new RecursiveArrayIterator($data),
RecursiveIteratorIterator::LEAVES_ONLY
) as $value) {
$result[] = array('id' => $value);
}
var_dump($result);
$array = [
[1, 30, 33],
['id' => 5]
];
$result = array_reduce($array, function (array $result, array $array) {
return array_merge($result, array_map(
function ($id) { return compact('id'); },
array_values($array)
));
}, []);
var_dump($result);
Admittedly not the simplest way to solve this, but very "functional". ;)
$array = array(
array(0 => 1,1 => 30,2 => 33,),
array("id" => 5,)
);
$result = array_merge(
array_map('array_flip',
array_chunk(
array_fill_keys($array[0], "id"),
1, true)
),
array_slice($array, 1)
);
var_export($result);
Results in:
array (
array ( 'id' => 1 ),
array ( 'id' => 30 ),
array ( 'id' => 33 ),
array ( 'id' => 5 )
)

loop through array adding previous value to current value

I wish to loop through an array adding the previous value to the current one. This is my latest attempt, but does not output the desired result
$array = array(
"myKeyName" => 3,
"anotherName" => 8,
"aKeyName" => 12,
"keyName" => 6,
"anotherKey" => 34
);
$setItems = array();
$i = 1;
foreach($array as $key => $val){
$setItems['item'.$i] = $val+$val;
$i++;
};
print_r($setItems);
OUTPUT
Array ( [item1] => 6 [item2] => 16 [item3] => 24 [item4] => 12 [item5] => 68 )
DESIRED OUTPUT
Array ( [item1] => 3 [item2] => 11 [item3] => 23 [item4] => 29 [item5] => 63 )
I understand why I am getting the current output, I just don;t know how to change it get get the desired output efficiently. Any ideas?
$array = array(
"myKeyName" => 3,
"anotherName" => 8,
"aKeyName" => 12,
"keyName" => 6,
"anotherKey" => 34
);
$setItems = array();
$i = 1;
$previous = 0;
foreach($array as $key => $val){
$setItems['item'.$i] = $val+$previous;
$previous += $val;
$i++;
};

build an array multidimensional from query results

I have this code that outputs something like:
Array (
[0] => 15
[1] => 13
[2] => 16
[3] => 16
[4] => 10
[5] => 10
[6] => 13
[7] => 13
)
But, i want this structure:
Array (
[0] => Array ( [0] => 15, [1] => 13, [2] => 16, [3] => 16)
[0] => Array ( [0] => 10, [1] => 10, [2] => 13, [3] => 13)
)
This didn't solve : $score[] = array($score_bd);. Any idea ?
php code
$i =0;
foreach ($arr_user_apply as $val) {
$new_val = array($val);
$arr[$i] = array_merge($str, $new_arr_tags_ids, $new_val, $new_id_oferta);
$sql = $db -> prepare("
query
"
);
call_user_func_array(array($sql, "bind_param"), $arr[$i]);
$sql -> execute();
$sql -> bind_result($score_bd);
while ($sql -> fetch()) {
$score[] = $score_bd;
};
$i++;
}
If you're just trying to add another dimension to your first array by placing the key value of the key into the new array something like this might work:
$firstArray = Array ( 0 => 15, 1 => 15, 2 => 13, 3 => 13, 4 => 16, 5 => 16, 6 => 10, 7 => 10, 8 => 13, 9 => 13, 10 => 6, 11 => 6 );
$newArray = Array();
foreach($firstArray as $key => $value)
{
$newArray[] = Array($key => Array($value));
}
echo "<pre>";
print_r($newArray);
echo "</pre>";
EDIT:
if that's one dimension too deep, then just try this:
$firstArray = Array ( 0 => 15, 1 => 15, 2 => 13, 3 => 13, 4 => 16, 5 => 16, 6 => 10, 7 => 10, 8 => 13, 9 => 13, 10 => 6, 11 => 6 );
$newArray = Array();
foreach($firstArray as $key => $value)
{
$newArray[$key] = Array($value);
}
echo "<pre>";
print_r($newArray);
echo "</pre>";
$arr = array ( 0 => 15 ,1 => 15, 2 => 13, 3 => 13 ,4 => 16 ,5 => 16 ,6 => 10, 7 => 10);
foreach($arr as $key=>$value){
$new_arr[$key][0] = $value;
}
i am not sure if the question is clear, but this works properly to me
$score = array();
while ($sql -> fetch()) {
$score[] = $score_bd;
};
$new_score[] = array($score);
Array (
[0] => Array ( [0] => Array ( [0] => 15 [1] => 13 [2] => 16 ) )
[1] => Array ( [0] => Array ( [0] => 10 [1] => 13 [2] => 6 ) )
)

Categories