How to add the values of multidimensional arrays in PHP? - php

Problem solved thanks guys :
foreach($FIMP as &$value){
foreach($value as &$values){
$values[0]=$values[3].$values[2].$values[1];
}
I have the following arrays:
$FIMP=array(
1 => array(
1 => array('a','b','c')
2 => array('a1','b1','c1')
2 => array(
1 => array('a2','b2','c2')
3 => array(
1 => array('a3','b3','c3')
2 => array('a4','b4','c4')
3 => array('a5','b5','c5')
)
I want to add the the values: b and c and overwrite a with the 'bc'
result like this
$FIMP=array(
1 => array(
1 => array('bc','b','c')
2 => array('b1c1','b1','c1')
2 => array(
1 => array('b2c2','b2','c2')
...
I already tried $FIMP
foreach($FIMP as $value){
foreach($value as $values){
$values[0]=$values[3].$values[2].$values[1];
}
}
in the out put there is no change to the previous $FIMP ,

From the PHP foreach documentation:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
So to change the values in $FIMP, you need to change your foreach loop to the following:
foreach($FIMP as &$value){
foreach($value as &$values){
// alter $value or $values here
}
}

<?php
$FIMP=array(
1 => array(
1 => array('a','b','c'),
2 => array('a1','b1','c1'),
),
2 => array(
1 => array('a2','b2','c2'),
),
3 => array(
1 => array('a3','b3','c3'),
2 => array('a4','b4','c4'),
3 => array('a5','b5','c5'),
),
);
foreach($FIMP as & $v1){
foreach($v1 as & $v2){
$v2[0] = $v2[1].$v2[2];
}
}
var_dump($FIMP);

You can do it like this:
foreach($FIMP as &$first){
foreach($first as &$second){
$second[0] = $second[1].$second[2];
}
}
OUTPUT
Array
(
[1] => Array
(
[1] => Array
(
[0] => bc
[1] => b
[2] => c
)
[2] => Array
(
[0] => b1c1
[1] => b1
[2] => c1
)
)
[2] => Array
(
[1] => Array
(
[0] => b2c2
[1] => b2
[2] => c2
)
)
[3] => Array
(
[1] => Array
(
[0] => b3c3
[1] => b3
[2] => c3
)
[2] => Array
(
[0] => b4c4
[1] => b4
[2] => c4
)
[3] => Array
(
[0] => b5c5
[1] => b5
[2] => c5
)
)
)

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

Get particular data with multiple index value with/without loop in cakephp

I have an array in which i want only lineNo and Isdirty field in each array .
My demo code is
Array
(
[CodeConfiguration] => Array
(
[0] => Array
(
[ObjectType] => 12
[LineNo] => 1
[CompanyID] => 1
[BranchID] => 46
[ModifiedDate] => 2014-04-25 05:10:15
[RevisionNumber] => 6
[IsDirty] =>
)
)
[TaxConfiguration] => Array
(
[0] => Array
(
[LineNo] => 2
[IsDirty] => 1
[ItemGroupID] =>
[TaxID] =>
[CalculationType_080] => 430
[RevisionNumber] => 1
)
[1] => Array
(
[LineNo] => 1
[IsDirty] => 1
[ItemGroupID] =>
[TaxID] =>
[CalculationType_080] => 372
[RevisionNumber] => 1
)
)
)
Only LineNo And Isdirty field want in every index array .So please suggest me solution.
You can sue following;
$finalArr = array();
foreach ($arr as $key => $item) {
foreach ($item as $k => $v) {
$finalArr[$key][] = array(
"LineNo" => $v["LineNo"],
"IsDirty" => $v["IsDirty"]
);
}
}
Here is a working demo: Demo

Get information for an "unique id" from a multidimensional array

I have an array with this structure:
Array
(
[mysite] => Array
(
[0] => Array
(
[0] => uniqueid
[1] => brand
[2] => horsepower
[3] => topspeed
)
[1] => Array
(
[0] => uniqueid
[1] => brand
[2] => horsepower
[3] => topspeed
)
[2] => Array
(
[0] => uniqueid
[1] => brand
[2] => horsepower
[3] => topspeed
)
)
)
Every car has an "uniqueid" followed by brand, horsepower, etc.
If I want to get the information for a random car, I do it like this:
$rkey = array_rand($sites['mysite'], 1); // get a random key
$car_info = $myarray['mysite'][$rkey];
Do you have any ideas on how to get information by using a certain "uniqueid"
$car_info = "get the information of a car with a certain uniqueid";
Ty!
try,
Pass unique id inside the for loop you will get the desird result
It may help you,
$array = array(
0 => Array
(
0 => 'uniqueid0',
1 => 'brand',
2 => 'horsepower',
3 => 'topspeed',
),
1 => Array
(
0 => 'uniqueid1',
1 => 'brand',
2 => 'horsepower',
3 => 'topspeed',
),
2 => Array
(
0 => 'uniqueid2',
1 => 'brand',
2 => 'horsepower',
3 => 'topspeed',
),
3 => Array
(
0 => 'uniqueid3',
1 => 'brand',
2 => 'horsepower',
3 => 'topspeed',
),
);
foreach($array as $arr){
if($arr[0] == 'uniqueid2'){
$result = $arr;
break;
}
}
print_r($result );
output:
Array ( [0] => uniqueid2 [1] => brand [2] => horsepower [3] => topspeed )
if the uniqueid is unique across cars then you can try restructure the array as follows
if possible
Array (
[mysite] => Array
(
[uniqueid1] => Array
(
[0] => uniqueid1
[1] => brand
[2] => horsepower
[3] => topspeed
)
[uniqueid2] => Array
(
[0] => uniqueid2
[1] => brand
[2] => horsepower
[3] => topspeed
)
[uniqueid3] => Array
(
[0] => uniqueid3
[1] => brand
[2] => horsepower
[3] => topspeed
)
)
)
this way you can directly access the car for uniqueid and can also apply random logic
if not #Jevgeni Bogatyrjov solution works well
foreach ($myarray['mysite'] as $car) {
if($car[0] == $uniqueid) {
$car_info = $car;
break;
}
}
$uniqueid = 12345;
foreach ($myarray['mysite'] as $car) {
if($car[0] == $uniqueid) {
$car_info = $car;
break;
}
}

How to combine arrays from a multidimensional array and count values?

I'm a beginner at php and was searching for a solution all day long without success.
I have the following array:
$data = Array
(
[0] => Array
(
[my_id] => 1
[my_post_id] => 123
[my_status] => 1
[my_rating] => 5
)
[1] => Array
(
[my_id] => 2
[my_post_id] => 123
[my_status] => 1
[my_rating] => 4
)
[2] => Array
(
[my_id] => 3
[my_post_id] => 123
[my_status] => 1
[my_rating] => 5
)
[3] => Array
(
[my_id] => 4
[my_post_id] => 456
[my_status] => 1
[my_rating] => 5
)
[4] => Array
(
[my_id] => 5
[my_post_id] => 456
[my_status] => 1
[my_rating] => 3
)
)
and would like to merge the arrays with the same 'my_post_id' and count the values for 'my_status' and 'my_rating' which have the same 'my_post_id'.
At the end, I would like to have the following array:
$data = Array
(
[0] => Array
(
[my_post_id] => 123
[my_status] => 3
[my_rating] => 14
)
[1] => Array
(
[my_post_id] => 456
[my_status] => 2
[my_rating] => 8
)
)
I could get arrays with unique 'my_post_id' with the following code but I couldn't find out how to count the other values.
$out = array();
foreach( $data as $row ) {
$out[$row['my_post_id']] = $row;
}
$array = array_values( $out );
Any help would be much appreciated.
Daniel
This will produce the array you are looking for:
$out = array();
foreach( $data as $row ) {
if (!isset($out[$row['my_post_id']])) {
$out[$row['my_post_id']] = Array( "my_id"=>$row['my_id'],
"my_status" => $row["my_status"],
"my_rating" => $row["my_rating"]);
}
else {
$out[$row['my_post_id']]["my_status"] += $row["my_status"];
$out[$row['my_post_id']]["my_rating"] += $row["my_rating"];
}
}
results in:
Array
(
[123] => Array
(
[my_id] => 1
[my_status] => 3
[my_rating] => 14
)
[456] => Array
(
[my_id] => 4
[my_status] => 2
[my_rating] => 8
)
)
try the following - untested code
foreach($data as $key => $val){
if(!array_search($val['my_post_id'],$newArray)){
$newArray[]=array('my_post_id' => $val['my_post_id'],
'my_status' => $val['my_status'],
'my_rating' => $val['my_rating']);
}else{
$myIndex=array_search($val['my_post_id'],$newArray);
$newArray[$myIndex]['my_status']+=$val['my_status'];
$newArray[$myIndex]['my_rating']+=$val['my_rating'];
}
}

Categories