I have this array :
$arr = array(0 => array('id' => "AMO"), 1 => array('id' => "PAT"));
And I would like to obtain this one :
array(
'AMO' => array(),
'PAT' => array()
)
How could I do this, in the shortest way possible ?
I can do it with an array_map, followed by an array_flip and next an array_walk .. but too long.
array_column to extract the keys and array_fill_keys to create the new array:
$arr = array(0 => array('id' => "AMO"), 1 => array('id' => "PAT"));
$res = array_fill_keys(array_column($arr, 'id'), []);
simply loop over array and make its id to new array key
$arr = array(0 => array('id' => "AMO"), 1 => array('id' => "PAT"));
foreach($arr as $value)
{
$new_arr[$value['id']] = array();
}
print_r($new_arr);
DEMO
I dont know what is the logic behind this, but you can try this one.
Here we are using array_combine, array_keys and array_fill
Try this code snippet here
$result= array_combine(
array_column($array,"id"),//getting column id
array_fill(0, count($array), array())//mapping that keys with empty array
);
Related
I'm trying to use array_sum() on columns within columns of a multidimensional array.
For eg: I have an array that looks like this:
$array = [
[['value' => 1100], ['value' => 1000], ['value' => 3000]],
[['value' => 1200], ['value' => 2000], ['value' => 2000]],
[['value' => 1300], ['value' => 4000], ['value' => 1000]],
];
I tried with:
$arr = [];
foreach($array as $point){
$arr[] = array_sum(array_column($array, $point[0]['value']));
}
print_r($arr);
but I'm expecting this output:
[['value' => 3600], ['value' => 7000], ['value' => 6000]]
Or more simply: [3600, 7000, 6000]
Tested here: https://onecompiler.com/php/3y3mxqky9
You can sum your columns doing like this:
foreach($array as $key => $point){
$arr[] = array_sum(array_column( array_column($array,$key),'value'));
}
print_r($arr);
Since you wish to have the sum vertically and not horizontally, the array_column style you used won't work. You can simply achieve this with 2 nested loops like below:
<?php
$arr = [];
foreach($array as $point){
foreach($point as $k => $v){
$arr[$k] = ($arr[$k] ?? 0) + $v['value'];
}
}
print_r($arr);
Online Demo
Transpose your input array, then isolate and sum the value column of data.
The variadic offering of $array to array_map() is the transposing part.
In other words, array_map(fn(...$col) => $col, ...$array) converts rows of data into columns of data.
Code: (Demo)
var_export(
array_map(
fn(...$col) => array_sum(array_column($col, 'value')),
...$array
)
);
Output:
array (
0 => 3600,
1 => 7000,
2 => 6000,
)
How to check two arrays and search for matching keys and merge the values of the 1st array with the matching keys of the second array.Please help me as I'm new to this.
example :
1st array = {id => 11,name => 'name',age => 18 }
2nd array = {id,name,age,school}
I want to get the result by adding the matching values to the 2nd array
2nd array = {id => 11,name => 'name',age => 18,school => }
try this
$a = ['id' => 11,'name' => 'name','age' => 18];
$b = array_flip(['id','name','age','school']);
foreach($b as $key => &$value){
$value = '';
}
$result = array_merge($b, $a);
One of the simple way is looping
$first= array('id' => 11,'name' => 'name','age' => 18 );
$second = array('id','name','age','school');
foreach ($second as $value) {
if(isset($first[$value])){
$final[$value] = $first[$value];
}
};
print_r($final);
Second Array flip and array merge
$first = ['id' => 11,'name' => 'name','age' => 18];
$second= array_flip(['id','name','age','school']);
foreach($second as $key => s$value){
$value = '';
}
$result = array_merge($second, $first);
print_r($result);
Use array_merge
<?php
$array1 = array('id' => '11', 'name' => 'name', 'age' => 18);
$array2 = array('id','name','age','school');
$array3 = array_merge(array_fill_keys($array2, null), $array1);
print_r($array3);
?>
I have two arrays. One has group names the other one has group items. I want to assign group names as keys to the second array.
Example:
$array1 = array(
0 => "A",
1 => "B"
);
$array2 = array(
0 => "a,b,c,d",
1 => "e,f,g,h"
);
The second array should become:
$array3 = array(
A => "a,b,c,d",
B => "e,f,g,h"
);
How can i achieve this in PHP?
Thanks
use array_combine as such :
$array2 = array_combine($array1, $array2);
you need to use array_combine, api here
would work like this:
<?php
$grpNames = array(0 => "A", 1 => "B");
$grpItems = array(0 => "a,b,c,d", 1 => "e,f,g,h");
$newArray = array();
foreach($grpItems as $grpItemKey => $grpItems){
if(isset($grpNames[$grpItemKey])){
$newArray[$grpNames[$grpItemKey]] = $grpItems;
}
}
var_dump($newArray);
?>
I've created a method that allows me to assign keys to rows of values, and appends extra keys and values.
It adds all the new keys to a keys array, then adds all new values to the values array, and then combines all the keys and values.
How can I shrink it to make it smaller and more efficient?
$valores = array(array("1","1","1","1"),array("2","2","2","2"));//array of values
$keys = array('k1','k2','k3','k4'); //array of keys
$id = array('SpecialKey' => 'SpecialValue');//new array of items I want to add
function formatarArray($arrValores,$arrKeys,$identificadores){
foreach($identificadores as $k => $v){
array_push($arrKeys, $k);
}
foreach($arrValores as $i => $arrValor)
{
foreach($identificadores as $k => $v){
array_push($arrValor, $v);
}
$arrValores[$i] = array_combine($arrKeys, $arrValor);
}
var_export($arrValores);
}
Output:
array (
0 =>
array (
'k1' => '1',
'k2' => '1',
'k3' => '1',
'k4' => '1',
'SpecialKey' => 'SpecialValue',
),
1 =>
array (
'k1' => '2',
'k2' => '2',
'k3' => '2',
'k4' => '2',
'SpecialKey' => 'SpecialValue',
),
)
Viper-7(code debug):
http://viper-7.com/hbE1YF
function formatarArray($arrValores, $arrKeys, $identificadores)
{
foreach ($arrValores as &$arr)
$arr = array_merge(array_combine($arrKeys, $arr), $identificadores);
print_r($arrValores);
}
Could even be done in one line...
function formatarArray($arrValores, $arrKeys, $identificadores)
{
print_r(array_map(function ($arr) use ($arrKeys, $identificadores) { return array_merge(array_combine($arrKeys, $arr), $identificadores); }, $arrValores));
}
As a modernized form of #havenard's answer, I'd use PHP7.4's arrow function syntax to avoid the need for use() and I would use the array union operator (+) to avoid the iterated array_merge() calls. The array union operator is appropriate because it is adding an associative array to another array.
Code: (Demo)
var_export(
array_map(
fn($row) => array_combine($keys, $row) + $id,
$valores
)
);
This question already has answers here:
Compare 2-dimensional data sets based on a specified second level value
(9 answers)
Closed last year.
I have two multidimensional arrays which are indexed arrays of associative rows.
$array1 = array(
array('name' => 'foo', 'id' => 12),
array('name' => 'bar', 'id' => 34),
array('name' => 'boo', 'id' => 56),
);
$array2 = array(
array('name' => 'bar', 'id' => 34),
array('name' => 'boo', 'id' => 56),
array('name' => 'bar', 'id' => 78),
);
It is possible that rows might have different id values but the same name value -- such as bar in my sample input data.
I need to compare the arrays based on id values only.
Expected Output: (because ids 34 and 56 are found in $array2)
array(
array('name' => 'foo', 'id' => 12)
)
I tried $one_not_two = array_diff($array1['id'], $array2['id']); which does not return anything.
I also tried $one_not_two = array_diff($array1['id'], $array2['id']);
which returned an error "argument is not an array."
Originally, I got around it by extracting the ids into a one-dimensional array, then just comparing those. Now a new feature in our application requires me to compare the rows while maintaining the multidimensional structure. Any advice?
Our servers are currently running php 5.3 if that makes any difference.
Because the arrays are multidimensional you have to extract the ids like this:
$ids1 = array();
foreach($array1 as $elem1)
$ids1[] = $elem1['id'];
$ids2 = array();
foreach($array2 as $elem2)
$ids2[] = $elem2['id'];
$one_not_two = array_diff($ids1,$ids2);
For your specific question, check out array_diff() with multidimensional arrays
You could use array_udiff to create a custom diff function:
$diff = array_udiff($array1,
$array2,
function ($a, $b){
if($a['id'] == $b['id']){
return 0;
} else {
return ($a['id'] < $b['id'] ? -1 : 1);
}
}
);
http://codepad.viper-7.com/2u5EWg
If id is unique you can do that:
$one_not_two = array();
foreach ($array1 as $val) {
$one_not_two[$val['id']] = $val;
}
foreach ($array1 as $val) {
if (!isset($one_not_two[$val['id']])) {
$one_not_two[$val['id']] = $val;
}
In the end I solved it by changing Array1 to an associative array of name => id
Having the same problem as you.
Solved it with: $result = array_diff_assoc($array2, $array1);
Reference: PHP: array_diff_assoc