I have 3 arrays as below.
$array1 = Array
(
[0] => 05/01
[1] => 05/02
)
$array2 =Array
(
[0] => ED
[1] => P
)
$array3 =Array
(
[0] => Mon
[1] => Tue
)
I want to merge these 3 arrays as below $result_array. I have written a code as below. But It gave a empty array.
$result_array =Array
(
[0] => Array
(
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array
(
[0] => 05/02
[1] => P
[2] => Tue
)
)
Code:
for($z=0; $z<count($array1); $z++){
$all_array[$z][] = array_merge($array1[$z],$array2[$z] );
$all_array2[$z] = array_merge($all_array[$z],$array3[$z] );
}
Please help me to do this.
Simply foreach over the first array and use the index as the key to the other arrays.
foreach ( $array1 as $idx => $val ) {
$all_array[] = [ $val, $array2[$idx], $array3[$idx] ];
}
Remember this will only work if all 3 arrays are the same length, you might like to check that first
You can simply walk through the first array with a foreach loop then access the corresponding arrays and combine the results into one big array. This will only work if the arrays are the same length so it's worth checking that before to stop any errors. Something like this:
<?php
$arr1 = ['05/01', '05/02'];
$arr2 = ['ED', 'P'];
$arr3 = ['Mon', 'Tue'];
$combined = [];
if (count($arr1) != count($arr2) || count($arr1) != count($arr3))
die("Array lengths do not match!");
foreach ($arr1 as $key => $val) {
$combined[] = [$val, $arr2[$key], $arr3[$key]];
}
var_dump($combined);
You can see an eval.in of this working here - https://eval.in/833893
Create an sample array and push to each array value with respective key
$sample = array();
for($z=0; $z<count($array1); $z++){
$sample[]=array($array1[$z],$array2[$z],$array3[$z]);
}
print_r($sample);
Out put is
Array ( [0] => Array (
[0] => 05/01
[1] => ED
[2] => Mon
)
[1] => Array (
[0] => 05/02
[1] => P
[2] => Tue
)
)
this work for n of arrays and dynamic length of array
function mergeArrays(...$arrays)
{
$length = count($arrays[0]);
$result = [];
for ($i=0;$i<$length;$i++)
{
$temp = [];
foreach ($arrays as $array)
$temp[] = $array[$i];
$result[] = $temp;
}
return $result;
}
$x = mergeArrays(['05/01' , '05/02'] , ['ED' , 'P'] , ['Mon' , 'Tus']);
$y = mergeArrays(['05/01' , '05/02' , 'X'] , ['ED' , 'P' , 'Y'] , ['Mon' , 'Tus' , 'Z'] , ['A' , 'B' , 'C']);
var_dump($x);
var_dump($y);
function merge($file_name, $titles, $description)
{
$result = array();
foreach($file_name as $key=>$name )
{
$result[] = array( 'file_name' => $name, 'title' => $titles[$key],
'description' => $description[ $key ] );
}
return $result;
}
$array1 = Array
(
'05/01',
'05/02'
);
$array2 = Array
(
'ED',
'P'
);
$array3 =Array
(
'Mon',
'Tue'
);
$result_array = array();
foreach ($array1 as $key=>$val)
{
$result_array[$key] = array($array1[$key],$array2[$key],$array3[$key]);
}
echo "<PRE>"; print_r($result_array);
Related
This is my form input $data, i want this keep this input.
$data = "39X3,29X5";
this my code convert string to array
$data = explode(",", $data);
$out = array();
$step = 0;
foreach($data as $key=>$item){
foreach(explode('X',$item) as $value){
$out[$key][$step++] = $value;
}
print '<pre>';
print_r($out);
print '</pre>';
result
Array
(
[0] => Array
(
[0] => 39
[1] => 3
)
[1] => Array
(
[2] => 29
[3] => 5
)
)
but i want change the keys and fix this for support query builder class
$this->db->insert_batch('mytable',$out).
Like this.
array
(
array
(
'number' => 39
'prize' => 3
),
array
(
'number' => 29
'prize' => 5
)
)
i try hard and confuse using loop.
So you need to remove inner foreach and put relevant values into array.
foreach($data as $key=>$item){
$exp = explode('X', $item);
$out[$key] = [
'number' => $exp[0],
'prize' => $exp[1]
];
}
Check result in demo
change your foreach loop to the following:
foreach($data as $key=>$item){
$temp = explode('X',$item);
$out[] = ['number' => $temp[0] , 'prize' => $temp[1]];
}
I need to sum the values in element 1 of my array where the values in element 0 are duplicate.
Here's a small piece of my array
Array
(
[0] => 3
[1] => 1
)
Array
(
[0] => 3
[1] => 2
)
Array
(
[0] => 3
[1] => 128
)
Array
(
[0] => 39
[1] => 4
)
The results i'm expecting to see
Array
(
[0] => 3
[1] => 131
)
Array
(
[0] => 39
[1] => 4
)
I'm still really new to PHP so any help is greatly appreciated.
You can use a combination of array_intersect, array_column and array_sum to only iterate twice. (One for each unique column 0 value).
$col0 = array_column($arr, 0);
$col1 = array_column($arr, 1);
Foreach(array_unique($col0) as $val){
$res[] = [$val, array_sum(array_intersect_key($col1, array_intersect($col0,[$val])))];
}
Var_dump($res);
https://3v4l.org/gKb5b
The way I've done it is made sure all duplicates where put in the same array.
// Your data
$sample = [[3, 1],[3, 2],[3, 128],[39, 4]];
foreach($sample as $array){
$tmp[$array[0]][] = $array[1];
}
# Output: {"3":[1,2,128],"39":[4]}
Now sum the arrays, and put it back to the structure it originally was.
foreach($tmp as $k => $v){
$new[] = [$k, array_sum($v)];
}
# Output: [[3,131],[39,4]]
But many roads lead to Rome.
Try this code. It may help you.
$array = array(["0" => 3, "1" => 1] , ["0" => 3, "1" => 2], ["0" => 3, "1" => 128], ["0" => 39, "1" => 4]);
$finalArray = [];
foreach($array as $a) {
$finalArray[$a[0]][0] = $a[0];
$finalArray[$a[0]][1] = !isset($finalArray[$a[0]][1]) ? $a[1] : $finalArray[$a[0]][1] + $a[1];
}
echo '<pre>';
print_r($finalArray);
exit;
You could do something like this. I have separated into two foreach. Hope it helps.
<?php
$a = [[3,1],[3,2],[3,128],[39,4]];
$result=[];
$temp = [];
foreach($a as $line) {
$temp[$line[0]] += $line[1];
}
foreach($temp as $k => $value) {
$result[]=[$k ,$value];
}
$data =
[
[3,1],
[3,2],
[3,128],
[39,4]
];
foreach($data as $item)
$sums[$item[0]] = ($sums[$item[0]] ?? 0) + $item[1];
$result = array_map(null, array_keys($sums), $sums);
var_export($result);
Output:
array (
0 =>
array (
0 => 3,
1 => 131,
),
1 =>
array (
0 => 39,
1 => 4,
),
)
$arr = [ [ 3, 1],[ 3, 2 ],[ 3, 128], [ 39, 4]];
$sum = [];
foreach($arr as $value) {
$sum[$value[0]][] = $value[1];
}
foreach($sum as $key=>$value ) {
$result[] = [ $key, array_sum($value)];
}
Output:
Array
(
[0] => Array
(
[0] => 3
[1] => 131
)
[1] => Array
(
[0] => 39
[1] => 4
)
)
I have an array as:
Array
(
[0] => Array
(
[0] => A
[1] => B
)
[1] => C
[2] => Array
(
[0] => D
[0] => E
)
)
and I want to convert it like:
Array
(
[0] => Array
[0] => A
[1] => B
[2] => C
[3] => D
[4] => E
)
i.e I want all the values in the first array (irrespective of their indexes) to be aligned in the second array.
You need to write a custom script which merge arrays by your logic.
Example:
<?php
$a = [
['A', 'B'],
'C',
['D', 'E']
];
$result = [];
foreach ($a as $v) {
if (is_array($v))
$result = array_merge($result, $v);
else
$result[] = $v;
}
print_r([$result]);
You can user this :
$array = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)),0);
I have copied from here how Turning multidimensional array into one-dimensional array
Please try with below code:
$arr = array(
0 => array("A", "B"),
1 => "C",
2 => array("D", "E"),
);
$result = array();
$response = arrayIndex($arr, $result);
function arrayIndex($arr, $result){
foreach ($arr as $key => $value) {
if(is_array($value)){
$result = $this->arrayIndex($value, $result);
} else {
array_push($result, $value);
}
}
return $result;
}
NOTE: This function will convert n level of array elements into a single level array.
I have two array and I need to merge it together !!
Array 1
Array
(
[0] => Array
(
[brand] => CARTIER
[amount_2014] => 136476
)
[1] => Array
(
[brand] => TIFFANY & CO.
[amount_2014] => 22000
)
[2] => Array
(
[brand] => Test
[amount_2014] => 33000
)
)
Array 2
Array
(
[0] => Array
(
[brand] => CARTIER
[amount_2013] => 22052
)
[1] => Array
(
[brand] => Test
[amount_2013] => 3313
)
)
I need the result array as:
Array
(
[0] => Array
(
[brand] => CARTIER
[amount_2014] => 136476
[amount_2013] => 22052
)
[1] => Array
(
[brand] => TIFFANY & CO.
[amount_2014] => 22000
[amount_2013] => 0
)
[2] => Array
(
[brand] => Test
[amount_2014] => 33000
[amount_2013] => 3313
)
)
So for every [brand] I need the amount in [amount_2014] & [amount_2013], if any one is not present then I need it value as 0;
I am using CodeIgniter for this project, I have only one table with field (brand, amount, year) am issuing two queries for getting sum of amount for 2013 & 2014.
(I am fighting with array_merge and array_combine but no use for me in this case, if any one can help with query then it's also very much helpful).
Try this:
function cars_array_merge()
{
$arrays = func_get_args();
foreach ($arrays as &$array)
{
$new_arr = array();
foreach ($array as $value)
{
$brand = $value['brand'];
unset($value['brand']);
$new_arr[$brand] = $value;
}
$array = $new_arr;
}
$arrays = call_user_func_array('array_merge_recursive', $arrays);
foreach ($arrays as $brand => &$array)
$array['brand'] = $brand;
return array_values($arrays);
}
// testing
$arr1 = [
[ 'brand' => 'CARTIER', 'mount_2014' => 136476 ],
[ 'brand' => 'TIFFANY & CO.', 'mount_2014' => 22000 ]
];
$arr2 = [
[ 'brand' => 'CARTIER', 'mount_2013' => 22052 ]
];
print_r(cars_array_merge($arr1, $arr2));
Output:
Array
(
[0] => Array
(
[mount_2014] => 136476
[mount_2013] => 22052
[brand] => CARTIER
)
[1] => Array
(
[mount_2014] => 22000
[brand] => TIFFANY & CO.
)
)
<?php
for ($i = 0, $max = count($arr1); $i < $max; ++$i) {
$arr1[$i]['amount_2013'] = isset($arr2[$i]['amount_2013']) ? $arr2[$i]['amount_2013'] : 0;
}
$merge = array_merge($arr1, $arr2);
$temp = $merge;
$newArr = array(); $key_array = array();
foreach($merge as $key=>$val){
$b = $val['brand'];
$a1 = isset($val['amount_2013']) ? $val['amount_2013'] : 0;
$a2 = isset($val['amount_2014']) ? $val['amount_2014'] : 0;
unset($temp[$key]);
foreach($temp as $k=>$values){
if($values['brand'] == $b){
if($a1 == 0){
$a1 = isset($values['amount_2013']) ? $values['amount_2013'] : 0;
}
if($a2 == 0){
$a2 = isset($values['amount_2014']) ? $values['amount_2014'] : 0;
}
unset($temp[$k]);
}
}
if(!in_array($b, $key_array))
{
$newArr[] = array('brand' => $b, 'amount_2014' => $a2, 'amount_2013' => $a1);
}
$key_array[] = $b;
}
print_r($newArr);
This is what I used:
<?php
$arr1 = array(0=>array("brand"=>"CARTIER","amount_2014"=>136476), 1=>array("brand"=>"tiffany","amount_2014"=>22000));
$arr2 = array(0=>array("brand"=>"CARTIER","amount_2013"=>22000));
foreach ($arr2 as $key=>$value){
if( $value["brand"] == "CARTIER")
{
$arr1[0]["amount_2013"] = $value["amount_2013"];
$arr1[1]["amount_2013"] = 0;
}
else
{
$arr1[1]["amount_2013"] = $value["amount_2013"];
$arr1[0]["amount_2013"] = 0;
}
}
print_r($arr1);
?>
--$arr1----
Array
(
[0] => Array
(
[id] => 1
[Name] => AAA
)
[1] => Array
(
[id] => 6
[Name] => BBB
)
)
--$arr2---
Array
(
[0] => Array
(
[id] => 1
[Name] => AAA
)
[1] => Array
(
[id] => 6
[Name] => BBB
)
[2] => Array
(
[id] => 46
[Name] => CCC
)
)
I would like the final result as following. Is there anyone can help me?
--Final Result--
Array
(
[0] => Array
(
[id] => 46
[Name] => CCC
)
)
UPDATE---
In this case, the result of array_diff($arr1,$arr2) is empty.
The easiest way is Mark Baker's solution or just write your own simple function:
Code:
function arrdiff($a1, $a2) {
$res = array();
foreach($a2 as $a) if (array_search($a, $a1) === false) $res[] = $a;
return $res;
}
print_r(arrdiff($arr1, $arr2));
Output:
Array
(
[0] => Array
(
[id] => 46
[name] => CCC
)
)
$arr1 = array(array('id' => 1, 'Name' => 'AAA'),
array('id' => 6, 'Name' => 'BBB')
);
$arr2 = array(array('id' => 1, 'Name' => 'AAA'),
array('id' => 6, 'Name' => 'BBB'),
array('id' => 46, 'Name' => 'CCC')
);
$results = array_diff(array_map('serialize',$arr2),array_map('serialize',$arr1));
$results = array_map('unserialize',$results);
var_dump($results);
EDIT
And just for the sheer fun of it, you could use array_filter() instead of array_diff() - which means no need to serialize anything at all
$results = array_filter($arr2, function ($value) use($arr1) { return !in_array($value,$arr1); } );
var_dump($results);
You should use array_diff():
$finalResult = array_diff($arr2, $arr1);
If you need more complex comparison you may also build foreach loop and use like this:
function compareItems( $a, $b){
return $a['id'] == $b['id']; // Example compare criteria
}
$result = array();
foreach( $arr1 as $item){
foreach( $arr2 as $key => $it){
if( !compareItems( $item, $it)){
$result[] = $it; // Either build new array
unset( $arr2[$key]); // Or remove items from original array
break;
}
}
}
And than you'll probably want to implement the same with reversed order of $arr1 and $arr2.
You can solve this with array_udiff()
function arr_comp($a, $b)
{
if ($a['id'] == $b['id'])
return 0;
else if ($a['id'] > $b['id'])
return 1;
else
return -1;
}
$result = array_udiff($arr2, $arr1, 'arr_comp');
or if you don't know in which array the differences may be you can try:
$res1 = array_udiff($arr1, $arr2, 'arr_comp');
$res2 = array_udiff($arr2, $arr1, 'arr_comp');
$result = array_merge($res1, $res2);
$arrDif=array();
$i=0;
foreach($arr1 as $value)
{
if(!in_array($value, $arr2))
{
$arrDif[$i]=$value;
$i++;
}
}
Take a look at the PHP built-in function array_diff. That'll help you out :-) Just pass your two arrays, and store the array returned by array_diff(), which will contain the differences between the two arrays.
As you're using multi-dimensional arrays, look at this comment on the PHP website: http://www.php.net/manual/en/function.array-diff.php#98680.