combine multiple arrays with order of key - php

For example I have like more than 3 different arrays, with element like below:
1st array
hello-1
hi-1
2nd array
ok-two
hi-2
22-two
hello
3rd array
hi-3rd
hello3
And so on...
I want to combine this array in the order one by one. For example the expected output for the 3 arrays above would be:
hello-1
ok-two
hi-3rd
hi-1
hi-2
hello3
22-two
hello
I tried array_merge(). But it appends the 2nd array after the complete 1st array, which is not what I'm looking for, so here I'm kinda stuck and don't know which functions I can use here. Any hints or ideas?

This should work for you:
First I get the first element of each array into a sub array, then the second value into the next sub array and so on, that you get this structure of array:
Array
(
[0] => Array
(
[0] => hello-1
[1] => ok-two
[2] => hi-3rd
)
//...
)
After this you can just loop through each array value with array_walk_recursive() and get every value into your array.
<?php
$arr1 = [
"hello-1",
"hi-1",
];
$arr2 = [
"ok-two",
"hi-2",
"22-two",
"hello",
];
$arr3 = [
"hi-3rd",
"hello3",
];
$arr = call_user_func_array("array_map", [NULL, $arr1, $arr2, $arr3]);
$result = [];
array_walk_recursive($arr, function($v)use(&$result){
if(!is_null($v))
$result[] = $v;
});
print_r($result);
?>
output:
Array
(
[0] => hello-1
[1] => ok-two
[2] => hi-3rd
[3] => hi-1
[4] => hi-2
[5] => hello3
[6] => 22-two
[7] => hello
)

I have another way to solve this issue
<?php
$arr1 = array(
"hello-1",
"hi-1");
$arr2 = array("ok-two",
"hi-2",
"22-two",
"hello");
$arr3 = array(
"hi-3rd",
"hello3");
$max = count($arr1);
$max = count($arr2) > $max ? count($arr2) : $max;
$max = count($arr3) > $max ? count($arr3) : $max;
$result = array();
for ($i = 0; $i < $max; $i++) {
if (isset($arr1[$i])) {
$result[] = $arr1[$i];
}
if (isset($arr2[$i])) {
$result[] = $arr2[$i];
}
if (isset($arr3[$i])) {
$result[] = $arr3[$i];
}
}
print_r($result);

Related

Combine same indexes of array

I have an array which as dynamic nested indexes in e.g. I am just using 2 nested indexes.
Array
(
[0] => Array
(
[0] => 41373
[1] => 41371
[2] => 41369
[3] => 41370
)
[1] => Array
(
[0] => 41378
[1] => 41377
[2] => 41376
[3] => 41375
)
)
Now I want to create a single array like below. This will have 1st index of first array then 1st index of 2nd array, 2nd index of first array then 2nd index of 2nd array, and so on. See below
array(
[0] =>41373
[1] => 41378
[2] => 41371
[3] => 41377
[4] => 41369
[5] => 41376
[6] => 41370
[7] => 41375
)
You can do something like this:
$results = [];
$array = [[1,2,3,4], [1,2,3,4], [1,2,3,4]];
$count = 1;
$size = count($array)-1;
foreach ($array[0] as $key => $value)
{
$results[] = $value;
while($count <= $size)
{
$results[] = $array[$count][$key];
$count++;
}
$count = 1;
}
I think you need something like this:
function dd(array $arrays): array
{
$bufferArray = [];
foreach($arrays as $array) {
$bufferArray = array_merge_recursive($bufferArray, $array);
}
return $bufferArray;
}
$array1 = ['41373','41371','41369','41370'];
$array2 = ['41378','41377', '41376', '41375'];
$return = array();
$count = count($array1)+count($array2);
for($i=0;$i<($count);$i++){
if($i%2==1){
array_push($return, array_shift($array1));
}
else {
array_push($return, array_shift($array2));
}
}
print_r($return);
first count the arrays in the given array, then count the elements in the first array, than loop over that. All arrays should have the same length, or the first one should be the longest.
$laArray = [
['41373','41371','41369','41370'],
['41378', '41377', '41376', '41375'],
['43378', '43377', '43376', '43375'],
];
$lnNested = count($laArray);
$lnElements = count($laArray[0]);
$laResult = [];
for($lnOuter = 0;$lnOuter < $lnElements; $lnOuter++) {
for($lnInner = 0; $lnInner < $lnNested; $lnInner++) {
if(isset($laArray[$lnInner][$lnOuter])) {
$laResult[] = $laArray[$lnInner][$lnOuter];
}
}
}
this would be the simplest solution:
$firstarr = ['41373','41371','41369','41370'];
$secondarr = ['41378','41377','41376','41375'];
$allcounged = count($firstarr)+count($secondarr);
$dividedintotwo = $allcounged/2;
$i = 0;
while ($i<$dividedintotwo) {
echo $firstarr[$i]."<br>";
echo $secondarr[$i]."<br>";
$i++;
}

Count how many times a value appears in this array?

I have this php array named $ids:
Array (
[0] => Array ( [id] => 10101101 )
[1] => Array ( [id] => 18581768 )
[2] => Array ( [id] => 55533322 )
[3] => Array ( [id] => 55533322 )
[4] => Array ( [id] => 64621412 )
)
And I need to make a new array containing each $ids id value, as the new keys, and the times each one appears, as the new values.
Something like this:
$newArr = array(
10101101 => 1,
18581768 => 1,
55533322 => 2,
64621412 => 1,
);
This is what I have:
$newArr = array();
$aux1 = "";
//$arr is the original array
for($i=0; $i<count($arr); $i++){
$val = $arr[$i]["id"];
if($val != $aux1){
$newArr[$val] = count(array_keys($arr, $val));
$aux1 = $val;
}
}
I supose array_keys doesn't work here because $arr has the id values in the second dimension.
So, how can I make this work?
Sorry for my bad english and thanks.
array_column will create an array of all the elements in a specific column of a 2-D array, and array_count_values will count the repetitions of each value in an array.
$newArr = array_count_values(array_column($ids, 'id'));
Or do it by hand like this where $arr is your source array and $sums is your result array.
$sums = array();
foreach($arr as $vv){
$v = $vv["id"];
If(!array_key_exists($v,$sums){
$sums[$v] = 0;
}
$sums[$v]++;
}
You can traverse your array, and sum the id appearance, live demo.
$counts = [];
foreach($array as $v)
{
#$counts[$v['id']] += 1;
}
print_r($counts);

create new array from existing array

I have multiple arrays like this:
array (
[floorBuildingName] => Array
(
[0] => Lt.1
[1] => Lt.2
)
[roomFloorName] => Array
(
[0] => Single
[1] => Medium1
[2] => MaXI
)
)
I would like to merge the two arrays into a single array.
For example:
array (
[0] => array(
[0] =>Lt.1,
[1] =>Single
),
[1] => array(
[0] =>Lt.2,
[1] =>Medium1
),
[2] => array(
[0] =>Lt.2,
[1] =>MaXI
)
)
How can I achieve this?
First, you have to determine the maximum array length. Then, create a new array and finally, put the elements at the given index into the new array. If the index is out of bounds, then use the last element.
var $maxNumber = 0;
foreach ($myArray as $array) {
$maxNumber = max($maxNumber, count($array));
}
$result = array();
for ($index = 0; $index < $maxNumber; $index++) {
$result[] = array();
foreach($myArray as $array) {
if (count($array) < $maxNumber) {
$result[$index][] = $array(count($array) - 1);
} else {
$result[$index][] = $array[$index];
}
}
}
Assuming that you want to pad out uneven arrays with the last value in the array:
$data = ['floorBuildingName' => [..], ..];
// find the longest inner array
$max = max(array_map('count', $data));
// pad all arrays to the longest length
$data = array_map(function ($array) use ($max) {
return array_pad($array, $max, end($array));
}, $data);
// merge them
$merged = array_map(null, $data['floorBuildingName'], $data['roomFloorName']);
You can do this using array_map very Easily:
Try this code:
$arr1 = array(1, 2);
$arr2 = array('one', 'two', 'three', 'four');
while(count($arr1) != count($arr2)) {
//If Array1 is Shorter then Array2
if (count($arr1)<count($arr2)) {
$arr1[] = $arr1[count($arr1) - 1];
}
//If Array2 is Shorter then Array1
if (count($arr1) > count($arr2)) {
$arr2[] = $arr2[count($arr2) - 1];
}
}
//Now merge arrays
$newarray = (array_map(null, $arr1, $arr2));
print_r($newarray);
Will Output:
Array
(
[0] => Array
(
[0] => 1
[1] => one
)
[1] => Array
(
[0] => 2
[1] => two
)
[2] => Array
(
[0] => 2
[1] => three
)
[3] => Array
(
[0] => 2
[1] => four
)
)
there's the solution for different number of arguments:
$floorBuildingName = array(
'Lt.1',
'Lt.2'
);
$roomFloorName = array(
'Single', 'Medium1', 'MaXI'
);
class ValueArrayIterator extends ArrayIterator
{
protected $arrays;
protected $latestValues = [];
public function __construct(array $mainArray) {
parent::__construct($mainArray);
$this->arrays = func_get_args();
}
public function current()
{
$returnValue = [];
foreach ($this->arrays as $arrayKey => $array) {
if (isset($array[$this->key()])) {
$this->latestValues[$arrayKey] = $array[$this->key()];
}
$returnValue[] = $this->latestValues[$arrayKey];
}
return $returnValue;
}
}
$iterator = new ValueArrayIterator($roomFloorName, $floorBuildingName);
$newArray = iterator_to_array($iterator);

mapping array in associative

I have the following array defined.
$a = Array
(
[0] => 30:27
[1] => 29:28
[2] => 30:27
)
$b = Array
(
[0] => 102186
[3] => 102991
[4] => 102241
)
I have used array_map($a,$b); But not what i want the result comes.
Always first to first key, second to second key, third to third key, I expect the following result...
$ab = $b = Array
(
[0] => 102186 [30:27]
[1] => 102991 [29:28]
[2] => 102241 [30:27]
)
Edit:
If the array keys doesn't match (thought it was a typo), then just reset the arrays by using $a = array_values($a) and $b = array_values($b) like this:
$a = array(
0 => "30:27",
1 => "29:28",
2 => "30:27"
);
$b = array(
0 => "102186",
3 => "102991",
4 => "102241"
);
// Reset keys
$a = array_values($a);
$b = array_values($b);
$ab = array();
for ($i=0; $i < count($a); $i++) {
$ab[] = "{$b[$i]} [{$a[$i]}]";
}
echo "<pre>";
print_r($ab);
echo "</pre>";
Outputs:
Array
(
[0] => 102186 [30:27]
[1] => 102991 [29:28]
[2] => 102241 [30:27]
)
Just loop over the 1st array and add the corresponding value from the 2nd one. You can actually use array_map for this:
$ab = array_map(function($aVal, $bVal){
return "$bVal [$aVal]";
}, $a, $b);
DEMO: https://eval.in/78684
USE:
$arrayFirst and $arraySecond - your input arrays;
$result = array();
for ($i=0; $i < count($arrayFirst); $i++) {
$result[] = "{$arraySecond[$i]} [{$arrayFirst[$i]}]";
}
var_dump ($result);
Or array_merge_recursive()
$array = array_merge_recursive($array1, $array2);

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