Combine array in PHP with values - php

Consider the below multi dimension array:
Array
(
[submit] => yes
[id] =>
[booking_id] =>
[booking_type_id] => Array
(
[0] => 171
[1] => 58
)
[value] => Array
(
[0] => 23
[1] => 46
)
)
How do I combine it so that that the booking_type_id and value arrays are in one array with the same values:
Array
(
[new_values] => Array
(
[171] => 23
[58] => 46
)
)
I have tried array_merge and array_combine, but I can't get it to keep the keys? I have also tried to loop through and add to a new array.

How did you use array_combine. That should work for the structure you want. Example below:
$multi = array(
'submit' => 'yes',
'id' => '',
'booking_id' => '',
'booking_type_id' => array( 171, 58 ),
'value' => array( 23, 46 ),
);
$combined = array_combine( $multi['booking_type_id'], $multi['value'] );

you can use array_combine() function like this:
$array['new_values'] = array_combine($array['booking_type_id'], $array['new_values']);

A simple solution would be to loop through the booking_type_id array and correlate those values in a new array with:
$array_1['booking_type_id'] = array(171,58);
$array_1['value'] = array(23,46);
$array_2 = array(); // new combined array
foreach ($array_1['booking_type_id'] as $key => $value) {
$array_2[$value] = $array_1['value'][$key];
}
With the result being:
Array
(
[171] => 23
[58] => 46
)
UPDATE:
As others have already noted you can also accomplish the same with array_combine()
$array_2 = array_combine( $array_1['booking_type_id'], $array_1['value'] );

<?php
$i = 0;
$new_values = array();
while($i < count($your_array['booking_type_id']))
{
$new_values['new_values'][$your_array['booking_type_id'][$i]] =
$your_array['value'];
$i++;
}
?>

$arr = array(
'submit' => "yes",
'id' => NULL,
'booking_id' => NULL,
'booking_type_id' => array(
0 => 171,
1 => 58
),
'value' => array(
0 => 23,
1 => 46
)
);
$new_arr = array();
foreach($arr['booking_type_id'] as $key=>$value){
$new_arr[$value] = $arr['value'][$key];
}
$arr['new_values'] = $new_arr;
echo"<pre>";print_r($arr);
Result will be
Array
(
[submit] => yes
[id] =>
[booking_id] =>
[booking_type_id] => Array
(
[0] => 171
[1] => 58
)
[value] => Array
(
[0] => 23
[1] => 46
)
[new_values] => Array
(
[171] => 23
[58] => 46
)
)

Related

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',
),
)

Multidimensional array to single array in PHP

I am working in PHP so I have an array like this, from this array I want filter take user_id to another array like I given below.
Array
(
[0] => Array
(
[user_id] => 66
[distance] => 0
)
[1] => Array
(
[user_id] => 68
[distance] => 0
)
[2] => Array
(
[user_id] => 81
[distance] => 0
)
[3] => Array
(
[user_id] => 65
[distance] => 0.00010218008081861118
)
)
I want an array like this,
$user_id=array(66,68,81,65);
Use array_column()
Returns an array of values representing a single column from the input array.
<?php
$user_array = array(
0 => array('user_id' => 1, 'name' => 'Bob'),
1 => array('user_id' => 2, 'name' => 'John'),
2 => array('user_id' => 3, 'name' => 'Mary')
);
$users = array_column($user_array, 'user_id');
print_r($users);
Output :
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Where $array is the multidimensional array you provided above:
$data = array();
foreach ($array as $item) {
$data[] = $item['user_id'];
}
print_r($data);

Filtering two php arrays

I have two arrays. I have combined both the arrays to output the total
1st array =
$farray = Array (
[0] => Array (
[1] => Array (
[ED] => 15
[EN] => 14
)
)
[1] => Array (
[2] => Array (
[ED] => 5
[EN] => 10
)
)
)
2nd Array =
$tarray = Array (
[0] => Array (
[1] => Array (
[ED] => 45
[EN] => 50
)
)
[1] => Array (
[2] => Array (
[ED] => 38
[EN] => 40
)
)
)
The combination of the above two arrays:
$all = Array (
[0] => Array (
[1] => Array (
[ED] => 60
[EN] => 64
)
)
[1] => Array (
[2] => Array (
[ED] => 43
[EN] => 50
)
)
)
Now I want to use the first array and the second array for inserting condition into the following codes:
$fscore = array_reduce(
$farray,
function($farray, $item) {
$id = key($item);
$scores = $item[$id];
$farray[$id] = array(
"score" => array_sum($scores),
"farray"=> min($scores)>=7
);
return $farray;
},
array()
);
The above attempt works and output the following (print_r($fscore)):
Array (
[1] => Array (
[score] => 124
[farray] => 1
)
[2] => Array (
[score] => 93
[farray] => 0
)
)
But I want to put more conditions to it and combine with the $tarray like below:
$all= array_reduce(
$all,
function($all, $item) {
$id = key($item);
$scores = $item[$id];
$all[$id] = array(
"score" => array_sum($scores),
"farray"=> min($scores)>=7
//if tarray key==ED 23 else 26 for minimum `$scores`
"tarray"=> min($scores)>='ED'? 23:26//ternary operator
);
return $all;
},
array()
);
I don't know how to insert the $tarray. As stated earlier, without the $tarray, it works.
My attempts failed and does not output expected result. In this question I only used ED and EN (score keys) to save more space. The minmum score expected for $farray is greater than or equal to 7 whereas the minimum score expected for $tarray is 23/26. If the score key is ED in $tarray, the minimum score is greater than or equal to 23, else it must be 26. Depending on those conditions, I want to return true or false value. Please help. Below is my attempt:
$farray = array(
array (
1=> array(
"ED"=>15,
"EN"=>14
)
),
array(
2=>array(
"ED"=>5,
"EN"=>10
)
)
);
$tarray = array (
array (
1 => array (
"ED" => 45,
"EN" => 50
)
),
array (
2 => array (
"ED" => 38,
"EN" => 40
)
)
);
$combine = array (
array (
1 => array (
"ED" => 60,
"EN" => 64
)
),
array (
2 => array (
"ED" => 43 ,
"EN" => 50
)
)
);
function filtertArray($value){
foreach($value as $key =>$val){
foreach($val as $k=>$v){
foreach($v as $t=>$m){
if($t=='ED'){
return $m>=23;
}else{
return $m>=26;
}
}
}
}
}
function filterfArray($value){
foreach($value as $key =>$val){
foreach($val as $k=>$v){
foreach($v as $t=>$m){
return $m>=7;
}
}
}
}
$all = array_reduce(
$combine,
function($combine, $item) use ($farray, $tarray) {
$id = key($item);
$scores = $item[$id];
$combine[$id] = array(
"score" => array_sum($scores),
"farray"=> array_filter($farray,"filterfArray"),
"tarray"=> array_filter($tarray,"filtertArray")
);
return $combine;
},
array()
);
echo "<pre>";
print_r($all);
echo "</pre>";
This outputs:
E_WARNING : type 2 -- Invalid argument supplied for foreach()
The expected output from this code is:
Array (
[1] => Array (
[score] => 124
[farray] => true//1
[tarray] => true//1
)
[2] => Array (
[score] => 93
[farray] => false//0
[tarray] => true//1
)
)
I don't think I'd bother trying to spice this answer up with an array_reduce() call. It is more important to comprehensibly deliver the correct comparisons and result. You are certainly welcome to convert my series of foreach loops to array functions.
My latest edit added more sample score data with the newly advised keys. The adjustment to $fscore's tarray comparison is that now the lowest non-ED score is compared against 26.
Code: (Demo)
$farray=[[1=>['ED'=>15,'EN'=>14,'MT'=>16,'MZ'=>20]],[2=>['ED'=>5,'EN'=>10,'MT'=>36,'MZ'=>30]]];
$tarray=[[1=>['ED'=>45,'EN'=>50,'MT'=>28,'MZ'=>27]],[2=>['ED'=>38,'EN'=>40,'MT'=>56,'MZ'=>60]]];
// generate $all
foreach($farray as $i=>$a){
foreach($a as $n=>$scores){
foreach($scores as $k=>$v){
$all[$i][$n][$k]=$v+$tarray[$i][$n][$k]; // sum the relative scores
}
}
}
var_export($all);
echo "\n\n";
// generate $fscores
$sub23_keys=array_flip(['ED']); // store list of keys that have lower score minimum
foreach($all as $i=>$a){
foreach($a as $n=>$scores){
$fscores[$n]['score']=array_sum($scores);
$fscores[$n]['farray']=min($farray[$i][$n])>=7; // check that both ED and EN scores are >=7
$fscores[$n]['tarray']=min(array_intersect_key($tarray[$i][$n],$sub23_keys)) && min(array_diff_key($tarray[$i][$n],$sub23_keys))>=26;
}
}
var_export($fscores);
Output:
// $all=
array (
0 =>
array (
1 =>
array (
'ED' => 60,
'EN' => 64,
'MT' => 44,
'MZ' => 47,
),
),
1 =>
array (
2 =>
array (
'ED' => 43,
'EN' => 50,
'MT' => 92,
'MZ' => 90,
),
),
)
//$fscores=
array (
1 =>
array (
'score' => 215,
'farray' => true,
'tarray' => true,
),
2 =>
array (
'score' => 275,
'farray' => false,
'tarray' => true,
),
)

merging mutidimensional arrays

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);
?>

Removing duplicates from multidimensional array based on the first elements only PHP

This is the array
Array
(
[0] => Array
(
[artist] => John Keys
[postID] => 254
)
[1] => Array
(
[artist] => Jay Bloom
[postID] => 249
)
[2] => Array
(
[artist] => John Keys
[postID] => 216
)
[3] => Array
(
[artist] => Angie Belle
[postID] => 225
)
)
and I want to remove all duplicates from the artist elements only. Notice that 0 and 2 have the same artist but a different postID. I just want to keep the first occurence of the artist and remove all others. So the result I want to have is
Array
(
[0] => Array
(
[artist] => John Keys
[postID] => 254
)
[1] => Array
(
[artist] => Jay Bloom
[postID] => 249
)
[2] => Array
(
[artist] => Angie Belle
[postID] => 225
)
)
I've tried array_unique and also serializing and doing an array_map, nothing seems to work right.
<?php
$array = Array
(
'0' => Array
(
'artist' => 'John Keys',
'postID' => 254
),
'1' => Array
(
'artist' => 'Jay Bloom',
'postID' => 249
),
'2' => Array
(
'artist' => 'John Keys',
'postID' => 216
),
'3' => Array
(
'artist' => 'Angie Belle',
'postID' => 225
)
);
$newarray = array();
foreach($array as $key => $val){
if(!array_key_exists('artist', $newarray)){
$newarray[$val['artist']] = $val;
}
}
echo '<pre>';
print_r($newarray);
Edit: using numeric keys:
$newarray = array();
$temp = array();
foreach($array as $key => $val){
if(!in_array($val['artist'], $temp)){
$temp[] = $val['artist'];
}
if( !array_key_exists(array_search($val['artist'], $temp), $newarray) ){
$newarray[array_search($val['artist'], $temp)] = $val;
}
}
Simple approach:
$result = array();
foreach ($input as $item) {
if (!array_key_exists($item['artist'], $result)) {
$result[$item['artist']] = $item;
}
}
<?php
$a=array(
"0" => array
(
"artist" => "John Keys",
"postID" => "254"
),
"1" => array
(
"artist" => "Jay Bloom",
"postID" => "249"
),
"2" => array
(
"artist" => "John Keys",
"postID" => "216"
),
"3" => array
(
"artist" => "Angie Belle",
"postID" => "225"
)
);
var_dump($a);
for($i=0;$i<count($a);$i++)
{
for($j=$i+1;$j<count($a); $j++)
{
$tmp1=$a[$i]["artist"];
$tmp2=$a[$j]["artist"];
if($tmp1==$tmp2)
{
unset($a[$j]);
}
$tmp3=array_values($a);
$a=$tmp3;
}
}
var_dump($a);
?>

Categories