merging subarrays of multidimensional arrays while sorting array alphabetically - php

Trying to alphabetically merge arrays with foreach loop.
<?php
$fruits = array(
'Apple' => array('ids'=>array(1,2)),
'Banana' => array('ids'=>array(3,4)),
'Ananas' => array('ids'=>array(5,6))
);
$result = array();
foreach ($fruits as $name=>$subarr) {
$first_letter = mb_substr($name, 0, 1);
$result[$first_letter] = $subarr;
}
print_r($result);
gives me smth like
Array
(
[A] => Array
(
[ids] => Array
(
[0] => 5
[1] => 6
)
)
[B] => Array
(
[ids] => Array
(
[0] => 3
[1] => 4
)
)
)
instead of smth like
[A] => Array
(
[ids] => Array
(
[0] => 1
[1] => 2
[2] => 5
[3] => 6
)
)
how can I fix it?

You overwrite your result every iteration in this line:
$result[$first_letter] = $subarr;
Just create a new array if the subArray in the result array doesn't exists and merge the ids subArray into your result array.
foreach ($fruits as $name=>$subarr) {
$first_letter = mb_substr($name, 0, 1);
if(!isset($result[$first_letter]))
$result[$first_letter] = [];
$result[$first_letter] = array_merge($result[$first_letter], $subarr["ids"]);
}

Please try to use foreach loop.
$fruits = array(
'Apple' => array('ids'=>array(1,2)),
'Banana' => array('ids'=>array(3,4)),
'Ananas' => array('ids'=>array(5,6))
);
$result = array();
foreach ($fruits as $name=>$subarr) {
$first_letter = mb_substr($name, 0, 1);
foreach($subarr as $key=>$value){
foreach ($value as $gkey => $gvalue) {
$result[$first_letter]['ids'][] = $gvalue;
}
}
}
echo "<pre>";
print_r($result);
Display above code output like below.
Array
(
[A] => Array
(
[ids] => Array
(
[0] => 1
[1] => 2
[2] => 5
[3] => 6
)
)
[B] => Array
(
[ids] => Array
(
[0] => 3
[1] => 4
)
)
)

Related

Combine two array and add value of array count

I have two array like this
$arr1 = array('Prabhash', 'Nagda', 'Sayyed','Prabhash');
$arr2 = array('4', '1', '2','5');
echo "<pre>";
print_r($arr1);
print_r($arr2);
And I want output like this
Array
(
[0] => Array
(
[0] =>Prabhash
[1] =>9
)
[1] => => Array
(
[0] =>Nagda
[1] =>1
)
[2] => => Array
(
[0] =>Sayyed
[1] =>2
)
)
I have tried to combine and merge array but not success, Hope someone will help me for this better.
PHP code demo
<?php
$arr1 = array('Prabhash', 'Nagda', 'Sayyed','Prabhash');
$arr2 = array('4', '1', '2','5');
$result=array();
foreach($arr1 as $key => $value)
{
if(isset($result[$value]))
{
$result[$value][1]+=$arr2[$key];
}
else
{
$result[$value]=array($value,$arr2[$key]);
}
}
$result= array_values($result);
print_r($result);
Output:
Array
(
[0] => Array
(
[0] => Prabhash
[1] => 9
)
[1] => Array
(
[0] => Nagda
[1] => 1
)
[2] => Array
(
[0] => Sayyed
[1] => 2
)
)
Short solution using array_map, array_keys, array_flip, array_unique, array_intersect_key and array_sum functions:
$arr1 = array('Prabhash', 'Nagda', 'Sayyed','Prabhash');
$arr2 = array('4', '1', '2','5');
$result = array_map(function($n) use($arr1, $arr2){
$sum = array_sum(array_intersect_key($arr2, array_flip(array_keys($arr1, $n))));
return [$n, $sum];
}, array_unique($arr1));
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => Prabhash
[1] => 9
)
[1] => Array
(
[0] => Nagda
[1] => 1
)
[2] => Array
(
[0] => Sayyed
[1] => 2
)
)
Try it.
<?php
$arr1 = array('Prabhash', 'Nagda', 'Sayyed','Prabhash');
$arr2 = array('4', '1', '2','5');
$newArray = array();
foreach($arr1 as $key => $value) {
$newArray[$value][0] =$value;
if(!isset($newArray[$value][1]) || $newArray[$value][1] == null)
$newArray[$value][1] = $arr2[$key];
else
$newArray[$value][1] = $newArray[$value][1]+$arr2[$key];
}
$newArray = array_values($newArray);
echo "<pre>";
print_r($newArray);
?>
OUTPUT :
Array
(
[0] => Array
(
[0] => Prabhash
[1] => 9
)
[1] => Array
(
[0] => Nagda
[1] => 1
)
[2] => Array
(
[0] => Sayyed
[1] => 2
)
)

merging two array in php

I have two arrays
$arr1=Array
(
[0] => Array
(
[0] => 'a'
),
[1]=>Array
(
[0]=>'b'
),
[2] => Array
(
[0] => 'c'
),
[3]=>Array
(
[0]=>'d'
),
[4]=>Array
(
[0]=>'e'
)
);
$arr2=array('1','2');
output should be
$arr3=Array
(
[0] => Array
(
[0] => 'a',
[1]=>'1'
),
[1]=>Array
(
[0]=>'b',
[1]=>'2'
),
[2] => Array
(
[0] => 'c',
[1]=>'1'
),
[3]=>Array
(
[0]=>'d',
[1]=>'2'
),
[4]=>Array
(
[0]=>'e',
[1]=>'1'
)
);
can someone please suggest me some solutions
You can do this with a MultipleIterator and attach the first array as ArrayIterator and the second one as InfiniteIterator, e.g.
<?php
$arr1 = [["a"], ["b"], ["c"], ["d"], ["e"]];
$arr2 = [1,2];
$result = [];
$mIt = new MultipleIterator();
$mIt->attachIterator(new ArrayIterator($arr1));
$mIt->attachIterator(new InfiniteIterator(new ArrayIterator($arr2)));
foreach($mIt as $v)
$result[] = array_merge($v[0], [$v[1]]);
print_r($result);
?>
This version will allow $arr2 to contain any number of values, should that be a requirement:
<?php
$arr1 = [
['a'], ['b'], ['c'], ['d'], ['e'],
];
$arr2 = ['1', '2'];
// wrap the array in an ArrayIterator and then in an
// InfiniteIterator - this allows you to continually
// loop over the array for as long as necessary
$iterator = new InfiniteIterator(new ArrayIterator($arr2));
$iterator->rewind(); // start at the beginning
// loop over each element by reference
// push the current value in `$arr2` into
// each element etc.
foreach ($arr1 as &$subArray) {
$subArray[] = $iterator->current();
$iterator->next();
}
print_r($arr1);
This yields:
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 2
)
[2] => Array
(
[0] => c
[1] => 1
)
[3] => Array
(
[0] => d
[1] => 2
)
[4] => Array
(
[0] => e
[1] => 1
)
)
Hope this helps :)

How to concatenate arrays element recursively [duplicate]

This question already has answers here:
Joining similar data from two indexed arrays
(2 answers)
Closed 5 months ago.
I'm working on a project and I'm stacked since 2 days, this is my problem: I have two arrays and want to retrieve the second item in each object in Array_2 and concatenate it to the content of each object in first Array_1 in PHP.
Array_1
[[1453274700000,24011],[1453275000000,24222],[1453275300000,24284],[1453275600000,24331],...]
Array_2
[[1453274700000,51951],[1453275000000,52093],[1453275300000,52251],[1453275600000,52288],...]
Wanted_array
[[1453274700000,24011,51951],[1453275000000,24222,52093],[1453275300000,24284,52251],[1453275600000,24331,52288]...]
A functional solution:
$result = array_map(function (array $a1, array $a2) {
return array_merge($a1, [$a2[1]]);
}, $array_1, $array_2);
This assumes that all items are in order and only need to be merged by their order, not by their first value.
If you want $item[0] to define what "group" each value belongs to, you can iterate through the first array and save $item[0] as the key and $item[1] as the value. Do the same for the second array. Now iterate through the saved array for array1, and check if the saved array for array2 contains the same keys. Do the same for array2 (in case it has key that array1 doesn't have), and save it all to a new array:
<?php
$arr1 = array(
array('1453274700000',24011),
array('1453275000000',24222),
array('1453276000000',24222), // inexistent in $arr2
);
$arr2 = array(
array('1453275000000',52093),
array('1453274700000',51951),
array('1453273000000',24222), // inexistent in $arr1
);
$arr1dictionary = [];
$arr2dictionary = [];
$result = [];
foreach ($arr1 as $collection) {
$arr1dictionary[$collection[0]] = $collection[1];
}
foreach ($arr2 as $collection) {
$arr2dictionary[$collection[0]] = $collection[1];
}
foreach ($arr1dictionary as $key => $value) {
if (isset($arr2dictionary[$key])) {
$result[$key] = [$key, $value, $arr2dictionary[$key]];
} else {
$result[$key] = [$key, $value, null];
}
}
foreach ($arr2dictionary as $key => $value) {
if (isset($result[$key])) {
continue;
}
$result[$key] = [$key, null, $value];
}
$result = array_values($result);
print_r($result);
Output:
Array
(
[0] => Array
(
[0] => 1453274700000
[1] => 24011
[2] => 51951
)
[1] => Array
(
[0] => 1453275000000
[1] => 24222
[2] => 52093
)
[2] => Array
(
[0] => 1453276000000
[1] => 24222
[2] => (null, the value only exists in $arr1)
)
[3] => Array
(
[0] => 1453273000000
[1] => (null, the value only exists in $arr2)
[2] => 24222
)
)
DEMO
Use array_walk and add second item from $array2 if it exists.
$array1 = array(
array(1453274700000,24011),
array(1453275000000,24222),
array(1453275300000,24284),
array(1453275600000,24331)
);
$array2 = array(
array(1453274700000,51951),
array(1453275000000,52093),
array(1453275300000,52251),
array(1453275600000,52288),
);
array_walk($array1, function(&$item, $key) use ($array2){
if(isset($array2[$key][1])){
$item[] = $array2[$key][1];
}
});
print_r($array1);
Output
Array
(
[0] => Array
(
[0] => 1453274700000
[1] => 24011
[2] => 51951
)
[1] => Array
(
[0] => 1453275000000
[1] => 24222
[2] => 52093
)
[2] => Array
(
[0] => 1453275300000
[1] => 24284
[2] => 52251
)
[3] => Array
(
[0] => 1453275600000
[1] => 24331
[2] => 52288
)
)
EDIT
As #h2ooooooo pointed out that there could be possibility that array items are in random order. If array items can be in random order and they are matched with first index value, use this (works with PHP >= 5.5.0):
$array1 = array(
array(1453274700000,24011),
array(1453275000000,24222),
array(1453275300000,24284),
array(1453275600000,24331),
array(1453276000000,24222) // no match in $array2
);
$array2 = array(
array(1453275000000,52093),
array(1453274700000,51951),
array(1453275300000,52251),
array(1453275600000,52288),
);
array_walk($array1, function(&$item, $key) use ($array2){
// Find match in $array2
$array2_key = array_search($item[0], array_column($array2, 0));
// If match found
if($array2_key !== false && isset($array2[$array2_key][1])){
$item[] = $array2[$array2_key][1];
}
// No match
else{
$item[] = null;
}
});
print_r($array1);
OUTPUT
Array
(
[0] => Array
(
[0] => 1453274700000
[1] => 24011
[2] => 51951
)
[1] => Array
(
[0] => 1453275000000
[1] => 24222
[2] => 52093
)
[2] => Array
(
[0] => 1453275300000
[1] => 24284
[2] => 52251
)
[3] => Array
(
[0] => 1453275600000
[1] => 24331
[2] => 52288
)
[4] => Array
(
[0] => 1453276000000
[1] => 24222
[2] =>
)
)

Assigning an array as a value of another array

I have three arrays i need to create an array which can be multidimensional.
1st array
Array
(
[0] => Test_One
[1] => Test_two
)
2nd array
Array
(
[0] => www.link.com
[1] => www.link2.com
)
3rd array
Array
(
[0] => Song1
[1] => song2
)
What i want
Array
(
[www.link.com] => Array
(
[0] => Test_one
[1] => Song1
)
[www.link2.com] => Array
(
[0] => Test_two
[1] => Song2
)
)
Assuming that you have same number of elements in all three arrays:
<?php
$arr1 = Array
(
0 => "Test_One",
1 => "Test_two"
);
$arr2 = Array
(
0 => "www.link.com",
1 => "www.link2.com"
);
$arr3 = Array
(
0 => "Song1",
1 => "Song2"
);
$final = []; //for versions below PHP 5.4 use $final = array();
foreach($arr2 as $key=>$value) {
$final[$value] = [$arr1[$key],$arr3[$key]];
}
print_r($final);
will output:
Array
(
[www.link.com] => Array
(
[0] => Test_One
[1] => Song1
)
[www.link2.com] => Array
(
[0] => Test_two
[1] => Song2
)
)
Update: Simplified foreach loop. From Comments #uchiha
Assuming that you havn't same number of elements in all three arrays:
<?php
$arr1 = Array
(
0 => "Test_One",
1 => "Test_two"
);
$arr2 = Array
(
0 => "www.link.com",
1 => "www.link2.com"
);
$arr3 = Array
(
0 => "Song1",
);
$final = []; //for versions below PHP 5.4 use $final = array();
foreach($arr2 as $key=>$value) {
if(array_key_exists($key,$arr1)) {
$final[$value][] = $arr1[$key];
}
if(array_key_exists($key,$arr3)) {
$final[$value][] = $arr3[$key];
}
}
print_r($final);
Output:
Array
(
[www.link.com] => Array
(
[0] => Test_One
[1] => Song1
)
[www.link2.com] => Array
(
[0] => Test_two
)
)
Hope this help :)
<?php
$array1 = Array
(
'Test_One',
'Test_two'
);
$array2 = Array
(
'www.link.com',
'www.link2.com'
);
$array3 = Array
(
'Song1',
'song2'
);
$array4 = array();
$i = 0;
foreach ($array2 as $a2){
$array4[$a2][] = $array1[$i];
$array4[$a2][] = $array3[$i];
$i++;
}
echo "<pre>";
print_r($array4);
?>

how to get array from get to normal array in php

I have an array like this and it can contain multiple values:
Array
(
[rpiid] => Array
(
[1] => 86
)
[sensor_id] => Array
(
[1] => 1
)
[when] => Array
(
[1] => 2014-02-24
)
[val] => Array
(
[1] => 000
)
[train] => Array
(
[1] => True
)
[valid] => Array
(
[1] => False
)
[button] => update
)
Of course, here there is only the number 1 each time but sometimes I have 0, 1, 2 and a value associated. This is because I get this from a GET from multiple forms.
How can I transform this array into
Array
(
[0] => Array
(
[rpiid] => 86
[sensor_id] => 1
...
Thanks,
John.
if your array is $get
$newArray = Array();
foreach($get as $secondKey => $innerArray){
foreach($value as $topKey => $value) {
$newArray[$topKey][$secondKey] = $value;
}
}
This should work
$new_array = array();
foreach($first_array as $value => $key){
$new_array[$key] = $value[1];
}
Sure you can, take a look at this small example:
$a = [ 'rpid' => [1], 'cpid' => [2,2] ];
$nodes = [];
foreach($a as $node => $array) {
foreach($array as $index => $value) {
if(empty($nodes[$index]))
$nodes[$index] = [];
$nodes[$index][$node] = $value;
}
}
print_r($nodes):
Array
(
[0] => Array
(
[rpid] => 1
[cpid] => 2
)
[1] => Array
(
[cpid] => 2
)
)

Categories