merging mutidimensional arrays - php

I have an array that looks like this:
getting array need to convert array as same key value as 0
foreach($array as $key=>$id){
$consumer_data[]=$this->App_model->get_session($id);
}
print_r($consumer_data);
Array
(
[0] => Array
(
[0] => Array
(
[ConsumerID] => 1
[name] => asdfd
)
[1] => Array
(
[ConsumerID] => 5
[name] => test
)
[2] => Array
(
[ConsumerID] => 3
[name] => test1
)
)
[1] => Array
(
[0] => Array
(
[ConsumerID] => 4
[name] => test4
)
)
i want to implement array like this in same key value as 0
Array
(
[0] => Array
(
[0] => Array
(
[ConsumerID] => 1
[name] => asdfd
)
[1] => Array
(
[ConsumerID] => 5
[name] => test
)
[2] => Array
(
[ConsumerID] => 3
[name] => test1
)
[3] => Array
(
[ConsumerID] => 4
[name] => test4
)
)
I am using PHP. Can anyone point me to a good starting point as to how I should go about doing this?

You can use array_merge():
$new_array[0] = array_merge($array[0], $array[1]);
Where $array is the first array.
SEE DEMO
OR for a more dynamic approach:
$new_array = array(0 => array());
foreach($array as $a) {
$new_array[0] = array_merge($new_array[0], $a);
}
SEE DEMO 2

The simpliest solution is to do it with:
$input = array(
array(
array('ConsumerID' => 1, 'name' => 'asdfd'),
array('ConsumerID' => 5, 'name' => 'test'),
array('ConsumerID' => 4, 'name' => 'test1'),
),
array(
array('ConsumerID' => 4, 'name' => 'test4'),
),
);
$output = array(
array()
);
foreach ($input as $data) {
$output[0] = array_merge($output[0], $data);
}

Try this->
$newArray = array();
foreach($values as $key=>$val){
$newArray [0][$key]=$val;
}
print_r($newArray);

Check this:
<?php
$arr[0] = array(0 => array("ConsumerID" => 1, "name" => "Ni"), 1 => array("ConsumerID" => 2, "name" => "Ab"));
$arr[1] = array(1 => array("ConsumerID" =>5, "name" => "GE"), 1 => array("ConsumerID" => 6, "name" => "DB"));
$new = array();
foreach($arr as $key => $value) {
foreach($value as $innerkey => $innervalue) {
$new[0][] = $innervalue;
}
}
print_r($new);
?>

Related

combine 2 array with same key into 1 array

I have 2 Array:
$arr1 = Array (
[2] => Array ( [0] => 41000 [1] => 31079 )
[3] => Array ( [0] => 42963 [1] => 41189 )
)
$arr2 = Array (
[2] => Array ( [0] => 40213 [1] => 42054 )
[3] => Array ( [0] => 42998 [1] => 34567 )
)
I want to combine these two arrays to this array with same key:
$arr3 = Array (
[2] => Array ( [0] => 40213 [1] => 42054 [2] => 41000 [3] => 31079 )
[3] => Array ( [0] => 42998 [1] => 34567 [2] => 42963 [3] => 41189 )
)
I tried almost anything (merge, combine, join) but I can't figure it out. Any suggestions?
This is a nice and easy thing to do.
$arr1 = [2 => [0 => 41000, 1 => 31079], 3 => [0 => 42963, 1 => 41189]];
$arr2 = [2 => [0 => 40213, 1 => 42054], 3 => [0 => 42998, 1 => 34567]];
function addArray(&$bucket, $water)
{
foreach ($water as $key => $drop) {
$bucket[$key] = array_merge($bucket[$key] ?? [], $drop);
}
}
$combined = [];
addArray($combined, $arr1);
addArray($combined, $arr2);
var_export($combined);
See a PHP fiddle here.
The output is:
array (
2 =>
array (
0 => 41000,
1 => 31079,
2 => 40213,
3 => 42054,
),
3 =>
array (
0 => 42963,
1 => 41189,
2 => 42998,
3 => 34567,
),
)
How does it work? I wrote a little function that would add the input arrays to an array that combines all arrays.
$arr1 = array(
2 => array(41000, 31079),
3 => array(42963, 41189)
);
$arr2 = array(
2 => array(40213, 42054),
3 => array(42998, 34567)
);
$arr3 = array();
foreach($arr1 as $key => $values){
if(!isset($arr3[$key])){
$arr3[$key] = array();
}
$arr3[$key] = array_merge($arr3[$key], $values);
}
foreach($arr2 as $key => $values){
if(!isset($arr3[$key])){
$arr3[$key] = array();
}
$arr3[$key] = array_merge($arr3[$key], $values);
}
echo '<pre>';
print_r($arr3);
Prints:
Array
(
[2] => Array
(
[0] => 41000
[1] => 31079
[2] => 40213
[3] => 42054
)
[3] => Array
(
[0] => 42963
[1] => 41189
[2] => 42998
[3] => 34567
)
)

Combining duplicate keys in a multidimensional array in PHP [duplicate]

This question already has answers here:
Group subarrays by one column, make comma-separated values from other column within groups
(2 answers)
Closed last month.
here's how it looks in the PHP code:
<?php
$array = array(
array(
'name' => 'filter_amount',
'value' => '100-ml'
),
array(
'name' => 'filter_amount',
'value' => '200-ml'
),
array(
'name' => 'page_size',
'value' => '7'
)
);
print_r($array);
?>
Example of print_r() function output:
Array
(
[0] => Array
(
[name] => filter_amount
[value] => 100-ml
)
[1] => Array
(
[name] => filter_amount
[value] => 200-ml
)
[2] => Array
(
[name] => page_size
[value] => 7
)
)
I need to combine duplicates of filter_amount values from the array.
The values of these duplicates must be commas separated and the result should be the following code:
Array
(
[0] => Array
(
[name] => filter_amount
[value] => 100-ml,200-ml
)
[1] => Array
(
[name] => page_size
[value] => 7
)
[2] => Array
(
[name] => orderby
[value] => rating
)
[3] => Array
(
[name] => paged
[value] => 1
)
)
Since you want value to be concatenated by a comma, you'll have to make a cycle of it
<?php
//Allow me to change this variable name, just to not create confusion
$content = array(
array(
'name' => 'filter_amount',
'value' => '100-ml'
),
array(
'name' => 'filter_amount',
'value' => '200-ml'
),
array(
'name' => 'page_size',
'value' => '7'
)
);
//$content is your initial array
//$outputArray is the final worked-up array
$outputArray = [];
//Let's make a cycle going for every array inside $content
foreach ($content as $innerArray) {
//Does this $innerArray['name'] (filter_ammount) exist in $outputArray in an array
//consisting in key => value where the key is 'name' and equals
//what we look for that is(filter_ammount)?
$key = array_search($innerArray['name'], array_column($outputArray , 'name'));
//If not, let's place this array in the $output array
if ($key === false) {
array_push($outputArray, $innerArray);
} else {
//If exists, then $key is the $key of the $outputArray and let's add to its value
//our current value, that is in our $innerArray, concatenated with a comma
$outputArray[$key]['value'] .= ",". $innerArray['value'];
}
}
//Boom, magic
print_r($outputArray);
//Note: This is going to affect every duplicate it finds, as in:
//If you got 3 arrays with name 'filter_ammount' and 2 arrays with name
//'page_size', it's going to concatenate the filter_ammount and the 'page_size'.
//If you specifically just want filter_ammount,
//replace this -> $key = array_search($innerArray['name'], array_column($outputArray , 'name'));
//with this -> $key = array_search('filter_ammount', array_column($outputArray , 'name'));
?>
References
http://php.net/manual/en/function.array-search.php
http://php.net/manual/en/function.array-column.php
How to combine two items by 2 duplicate columns?
[root#localhost TEST]# php R00.php
Array
(
[0] => Array
(
[0] => S01
[1] => 172.16.20.222
[2] => 10.10.10.100
[3] => 445
)
[1] => Array
(
[0] => S02
[1] => 10.10.10.10
[2] => 192.168.100.100
[3] => 22
)
[2] => Array
(
[0] => S03
[1] => 10.10.10.10
[2] => 192.168.100.100
[3] => 22
)
[3] => Array
(
[0] => S04
[1] => 172.16.20.222
[2] => 10.10.10.100
[3] => 23
)
[4] => Array
(
[0] => S05
[1] => 100.100.100.100
[2] => 192.168.100.100
[3] => 22
)
[5] => Array
(
[0] => S06
[1] => 192.168.200.10
[2] => 192.168.100.100
[3] => 22
)
[6] => Array
(
[0] => S07
[1] => 10.10.10.10
[2] => 192.168.100.100
[3] => 22
)
[7] => Array
(
[0] => S08
[1] => 192.168.100.100
[2] => 10.10.100.106
[3] => 446
)
[8] => Array
(
[0] => S09
[1] => 172.16.20.223
[2] => 10.10.10.108
[3] => 447
)
[9] => Array
(
[0] => S10
[1] => 192.168.100.100
[2] => 10.10.10.109
[3] => 448
)
)
[root#localhost TEST]#
combine 1 or 2 items by 2 column duplicate below is result I need
Array
(
[0] => Array
(
[0] => S01 , S04
[1] => 172.16.20.222
[2] => 10.10.10.100
[3] => 445 , 23
)
[1] => Array
(
[0] => S02 , S03 , S07
[1] => 10.10.10.10
[2] => 192.168.100.100
[3] => 22
)
[3] => Array
(
[0] => S05 , S06
[1] => 100.100.100.100 , 192.168.200.10
[2] => 192.168.100.100
[3] => 22
)
[4] => Array
(
[0] => S08
[1] => 192.168.100.100
[2] => 10.10.100.106
[3] => 446
)
[5] => Array
(
[0] => S09
[1] => 172.16.20.223
[2] => 10.10.10.108
[3] => 447
)
[6] => Array
(
[0] => S10
[1] => 192.168.100.100
[2] => 10.10.10.109
[3] => 448
)
)
Try this:
<?php
$array = array(
array(
'name' => 'filter_amount',
'value' => '100-ml'
),
array(
'name' => 'filter_amount',
'value' => '200-ml'
),
array(
'name' => 'page_size',
'value' => '7'
)
);
$tmp = array();
foreach($array as $val) {
$tmp[$val['name']]['values'][] = $val['value'];
}
foreach($tmp as $k => $v) {
$item = implode(',', array_unique(explode(',', implode(',',$v['values']))));
$newArr[] = array('name' => $k, 'value' => $item);
}
echo '<pre>';
print_r($newArr);
echo '</pre>';
got it with the following crazy mess:
$name = array_column($array, 'name');
$value = array_column($array, 'value');
foreach($name as $nk=>$nv)
foreach($value as $vk=>$vv)
if($nk == $vk)
$a[$nv][] = $vv;
foreach($a as $k=>$v)
$b[$k] = implode(',', $v);
$z = 0;
foreach($b as $k=>$v)
{
$c[$z]['name'] = $k;
$c[$z]['value'] = $v;
$z++;
}
$c is the resulting array
Or using a medley of array functions:
<?php
$array = array(
array(
'name' => 'filter_amount',
'value' => '100-ml'
),
array(
'name' => 'filter_amount',
'value' => '200-ml'
),
array(
'name' => 'page_size',
'value' => '7'
)
);
$names = array_column($array, 'name');
$values = array_column($array, 'value');
$result = [];
foreach (array_unique($names) as $k)
$result[$k] = implode(", ", array_filter($values,
function($v, $indx) use ($names, $k) {
return $names[$indx] == $k;
}, ARRAY_FILTER_USE_BOTH));
print_r($result);
$result2 = [];
foreach ($result as $k=>$v) $result2[] = ['name'=>$k, 'value'=>$v];
print_r($result2);
Results in:
Array
(
[filter_amount] => 100-ml, 200-ml
[page_size] => 7
)
Array
(
[0] => Array
(
[name] => filter_amount
[value] => 100-ml, 200-ml
)
[1] => Array
(
[name] => page_size
[value] => 7
)
)
All of the other answers up to now are using two or more iterating techniques for this task. There only needs to be one loop.
Build an associative output array based on the name values as you iterate. If the associative key isn't set, then save the whole row. If it is set, then just append a comma then the new value data to the stored value element.
Using temporary keys allows isset() to swiftly check for existence. It will always outperform array_search() and in_array() because of how php treats arrays (as hash maps).
Remove the temporary keys when the loop is finished by calling array_values().
Code: (Demo)
$result = [];
foreach ($array as $row) {
if (!isset($result[$row['name']])) {
$result[$row['name']] = $row;
} else {
$result[$row['name']]['value'] .= ',' . $row['value'];
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'name' => 'filter_amount',
'value' => '100-ml,200-ml',
),
1 =>
array (
'name' => 'page_size',
'value' => '7',
),
)

Store column data from a multidimensional array while preserving missing elements

I have an array ($myArray) which looks like
Array ( [0] =>
Array ( [0] =>
Array (
[Date] => 1776-08-08
[Color] => Yellow
[Description] => Rotten
) )
[1] => Array ( )
[2] =>
Array ([0] =>
Array (
[Date] => 2018-05-13
[Color] => Red
[Status] => Fresh
)
[1] =>
Array (
[Date] => 1991-03-29
[Color] => Green
[Status] => Fresh ) )
I loop though the content for the values of Date using
array_walk_recursive($myArray, function($v, $k){
if ($k == "Date") echo $v . PHP_EOL;
This would get me the correct output.
1776-08-08 2018-05-13 1991-03-29
I want to add the output into an array and even if the value is null (ie[1] above) to still set an empty array.
For example $newArray =
Array ( [0] => 1776-08-08 )
Array ( )
Array ( [0] => 2018-05-13 [1] => 1991-03-29 )
Given your example, an option is to use array_column() on each of the items in the outermost array, which is easy with the array_map() function.
$input = array(
array(
array(
"Date" => "1776-08-08",
"Color" => "Yellow",
"Description" => "Rotten",
),
),
array(
),
array(
array(
"Date" => "2018-05-13",
"Color" => "Red",
"Status" => "Fresh",
),
array(
"Date" => "1991-03-29",
"Color" => "Green",
"Status" => "Fresh",
),
),
);
$output = array_map(function($sub_arrays) {
return array_column($sub_arrays, "Date");
}, $input);
print_r($output);
The above will output something like:
Array
(
[0] => Array
(
[0] => 1776-08-08
)
[1] => Array
(
)
[2] => Array
(
[0] => 2018-05-13
[1] => 1991-03-29
)
)
You'll need to do a normal foreach loop for the top-level, and then use array_walk_recursive for the nested arrays.
$newArray = array();
foreach ($myArray as $el) {
$temp = array();
array_walk_recursive($el, function($v, $k) use (&$temp) {
if ($k == "Date") {
$temp[] = $v;
}
});
$newArray[] = $temp;
}
DEMO

Move value to next element of array

See the attached example that i use to build my array
foreach($something AS $key => $row)
{
$output[] = array("name"=>$row["name"], "points"=>$row["points"]);
}
print_r($output);
Here's the output:
Array
(
[0] => Array
(
[name] => Mark
[points] => 1
)
[1] => Array
(
[name] => Sara
[points] => 2
)
[2] => Array
(
[name] => Jack
[points] => 3
)
)
What i'm trying to do is moving $row["points"] to next array element to get this output:
Array
(
[0] => Array
(
[name] => Mark
[points] =>
)
[1] => Array
(
[name] => Sara
[points] => 1
)
[2] => Array
(
[name] => Jack
[points] => 2
)
)
I don't care if there's some data loss or if my [points] => 3 goes in a new array. I just have to programmatically move $row["points"] always to next element. I'm playing with next() function with no success and also with $key+1 which i'm sure i can't use to achieve the result.
Is it possible to make it on top while i'm building the array or am i forced to move the element later with a separate function? In other words what would you do?
Try This:
$output = array();
$something = array(
'0' => array(
'name' => 'Mark',
'points' => 1,
),
'1' => array(
'name' => 'Sara',
'points' => 2,
),
'2' => array(
'name' => 'Jack',
'points' => 3,
)
);
$point = '';
foreach($something AS $key => $row)
{
$output[$key] = array("name"=>$row["name"], "points"=>$point);
$point = $row['points'];
}
echo '<pre>';
print_r($output);
Try if it helps:
foreach($something AS $key => $row)
{
$output[$key]['name'] = $row["name"];
$output[$key+1]['points'] = $row["points"];
}
print_r($output);
Use:
foreach($array as $key => $each)
{
$array[0]['points'] = "";
$array[$key]['name'] = $each["name"];
if(isset($array[$key+1])) $array[$key+1]['points'] = $each["points"];
}
print_r($array);

How do I move array child value to parent key?

I need some clarity as to what PHP function can achieve what I'm aiming for.
This is a PHP array I have:
Array
(
[0] => Array
(
[id] => 6
[index] => 1
[active] => 1
[name] => MyName
)
[1] => Array
(
[id] => 1
[index] => 2
[active] => 1
[name] => YourName
)
[2] => Array
(
[id] => 2
[index] => 4
[active] => 1
[name] => TheirName
)
}
I want to take the "index" value and make it a KEY of that array parent, so the array would become this:
Array
(
[1] => Array
(
[id] => 6
[index] => 1
[active] => 1
[name] => MyName
)
[2] => Array
(
[id] => 1
[index] => 2
[active] => 1
[name] => YourName
)
[4] => Array
(
[id] => 2
[index] => 4
[active] => 1
[name] => TheirName
)
}
Can anyone please tell me how would I do this in PHP?
Thank you in advance.
you can use: array_column($array, null, 'index');
is the better solution, but only work for >= 5.5 php version
Not the most elegant solution, but it works (it doesn't actually move the array, it just generates a new one that corresponds to your requirements):
$resultArr = array();
foreach ($mainArr as $value) {
$resultArr[$value['index']] = $value;
}
unset($mainArr); // or $mainArr = $resultArr;
This way you won't overwrite any existing keys in your original array.
$a = array
(
0 => array
(
"id" => 6,
"index" => 1,
"active" => 1,
"name" => "MyName"
),
1 => Array
(
"id" => 1,
"index" => 2,
"active" => 1,
"name" => "YourName"
),
2 => Array
(
"id" => 2,
"index" => 4,
"active" => 1,
"name" => "TheirName"
)
);
$newArray = array();
foreach ($a as $foo) {
$newArray[$foo['index']] = $foo;
}
You have to do it manually with:
$input = array( /* your data */ );
$output = array();
foreach ( $input as $values ) {
$output[ $values['index'] ] = $values;
}
public static function normArray($key, $inputArray)
{
$outputArray = array();
foreach ($inputArray as $item) {
$index = intval($item[$key]);
$outputArray[$index] = $item;
}
return $outputArray;
}

Categories