I'm looking for an elegant way to turn this array:
Array (
[foo] => 1
[bar] => 1
[zim] => 3
[dib] => 6
[gir] => 1
[gaz] => 3
)
Into this array:
Array (
[1] => Array ( foo, bar, gir ),
[3] => Array ( zim, gaz ),
[6] => Array ( dib )
)
Note:, there is no relationship between the keys or values. They are completely arbitrary and used as examples only. The resulting array should be an associative array grouped by the values of the input array.
Thanks!
$input = array(
'foo' => 1,
'bar' => 1,
'zim' => 3,
'dib' => 6,
'gir' => 1,
'gaz' => 3
)
$output = array();
foreach ( $input as $k => $v ) {
if ( !isset($output[$v]) ) {
$output[$v] = array();
}
$output[$v][] = $k;
}
I think this will do it just fine:
foreach ($arr1 as $k => $val) $arr2[$val][] = $k;
where $arr1 is the original array outputting the new array to $arr2.
Related
I've been stuck on this for the better part of the day and I'm out of ideas. I have an array like this:
Array
(
[rank] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[name] => Array
(
[0] => 'Hideki'
[1] => 'Rory'
[2] => 'Sam'
[money] => Array
(
[0] => '$100'
[1] => '$200'
[2] => '$500'
)
)
and I have the task to create an array with the following format from it:
Array
(
[Hideki] => Array
(
[rank] => 1
[money] => '$100'
)
[Rory] => Array
(
[rank] => 2
[money] => '$200'
[Sam] => Array
(
[rank] => 3
[money] => '$500'
)
)
The catch is that 'rank' and 'money' have to be dynamic names
It should be simple as that:
$new = [];
foreach($array['name'] as $key => $name) {
$new[$name] = [
'rank' => $array['rank'][$key],
'money' => $array['money'][$key]
];
}
Little late but here my answear. My approach was to use the array_walk() function.
$array = [
'rank' => [1,2,3],
'name' => ['Hideki', 'Rory', 'Sam'],
'money' => ['$100', '$200', '$500'],
];
$i = 0;
$newArray = [];
array_walk($array['name'], function($name) use (&$i, $array, &$newArray) {
$newArray[$name] = ['rank'=> $array['rank'][$i], 'money' => $array['money'][$i]];
$i++;
});
print_r($newArray);
Run your first array through a foreach loop referencing only the "name" key and using key=>value pairs. Then reference the other keys from the first array when you build the new array, setting the value as the key to the second array.
You will need to first get the keys using array_keys() and use a nested foreach to loop through all the keys.
Example:
$keys1 = array_keys($array1);
foreach ($array1['name'] as $key => $value) {
$val2 = array();
foreach ($keys1 as $k){
if ($k != 'name') $val2[$k] = $array1[$k][$key];
}
$array2[$value] = $val2;
}
I have an array like below: all the values I am getting one array only, but I don't want this way. This is the best way to do so, in php or jQuery both languages are ok for me
Array
(
[0] => Array
(
[val] => facebook
)
[1] => Array
(
[val] => snapchat
)
[2] => Array
(
[val] => instagram
)
[3] => Array
(
[expenses] => 986532
)
[4] => Array
(
[expenses] => 45456
)
[5] => Array
(
[expenses] => 56230
)
[6] => Array
(
[social_id] => 15
)
[7] => Array
(
[social_id] => 16
)
[8] => Array
(
[social_id] => 17
)
)
and I want to output like this..
$result = array(
array(
"val" => "Facebook",
"expenses" => "84512",
"social_id" => 1
),
array(
"val" => "Instagram",
"expenses" => "123",
"social_id" => 2
)
);
but this should be dynamic, the length of the above array can be varies
You can merge the arrays to one and use array_column to get all vals or expenses in a separate array.
Then foreach one array and build the new array with the key.
//$a = your array
// Grab each column separate
$val = array_column($a, "val");
$expenses= array_column($a, "expenses");
$social_id = array_column($a, "social_id");
Foreach($val as $key => $v){
$arr[] = [$v, $expenses[$key], $social_id[$key]];
}
Var_dump($arr);
https://3v4l.org/nVtDf
Edit updated with the 'latest' version of the array. My code works just fine with this array to without any changes.
to get that array style you can do it by hand for each array
function test(array ...$arr)
{
$result = array();
foreach ($arr as $key => $pair) {
foreach ($pair as $item => $value) {
$result[$item] = $value;
}
}
return $result;
}
$arr1 = test( ['facebook' => 1], ['expenses' => 100]);
print_r($arr1);
/* Array (
[facebook] => 1,
[expenses] => 100
)
*/
$arr2 = test( $arr1, ['more info' => 'info'] );
print_r($arr2);
/* Array (
[facebook] => 1,
[expenses] => 100,
[more info] => info
)
*/
you can pass it any number of
['Key' => 'Pair']
array('Key' => 'Pair')
or even a previous made array and it will add them up into 1 big array and return it
I have three arrays:
$arr1 = Array (
[0] => 1001
[1] => 1007
[2] => 1006);
$arr2 = Array (
[0] => frank
[1] => youi
[2] => nashua);
$arr3 = Array (
[0] => getfrankemail
[1] => getyouiemail
[2] => getnashuaemail);
Is there a way to combine these arrays to get a multidimensional array like this:?
Array (
[0] => Array (
[0] => 1001
[1] => frank
[2] => getfrankemail)
[1] => Array (
[0] => 1007
[1] => youi
[2] => getyouiemail)
[2] => Array (
[0] => 1006
[1] => nashua
[2] => getnashuaemail)
);
edit: what you are really looking for is a php version of the zip method in ruby/python.
For your specific example array_map works nicely:
$result = array_map(null, $arr1, $arr2, $arr3);
Output:
array (
0 =>
array (
0 => 1001,
1 => 'frank',
2 => 'frankemail',
),
1 =>
array (
0 => 1007,
1 => 'youi',
2 => 'youiemail',
),
2 =>
array (
0 => 1006,
1 => 'nashua',
2 => 'nashuaemail',
),
)
Iterate on the first array (looks like those are ids), and you can match the key for each value to indexes in $arr2 and $arr3
$result = array();
foreach ($arr1 as $key => $value) {
$result[] = array($value, $arr2[$key], $arr3[$key]);
}
as #kingkero mentions in his answer, you will get errors if they keys do not exist, which you could check for and ignore any rows where that is the case.
$result = array();
foreach ($arr1 as $key => $value) {
if (!isset($arr2[$key]) || !isset($arr3[$key])) {
continue;
}
$result[] = array($value, $arr2[$key], $arr3[$key]);
}
You could use array_push($aContainer, $arr1); or $aContainer[] = $arr[1]
You can do this with a loop in which you access each of the three arrays with the same key.
$result = array();
$max = count($arr1);
for ($i=0; $i<$max; $i++) {
$result[] = array(
$arr1[$i],
$arr2[$i],
$arr3[$i],
);
}
This could fire an out of bounds exception, since it doesn't check whether or not $arrX[$i] exists. Can you be sure that it does?
My sorted array needs to be split up so that each created array has all of those associated with that value.
Array (
[NAME] => Array
(
[0] => Fooaz
[1] => bzdsfdasfz
[2] => Fooooooooo
)
[DESCRIPTION] => Array
(
[0] => Foo
[1] => Foo
[2] => Barrrr
)
)
For example, from that array I want to get two arrays. One containing:
[NAME]=>Array([0] => Fooooooooo), [DESCRIPTION]=>Array([0] => Barrrr):
The other containing the remaining elements.
What's an efficient way of doing this?
$arr = Array (
'NAME' => Array
(
0 => 'Fooaz',
1 => 'bzdsfdasfz',
2 => 'Fooooooooo'
),
'DESCRIPTION' => Array
(
0 => 'Foo',
1 => 'Foo',
2 => 'Barrrr'
)
);
$arr1 = array();
foreach ($arr as $key => $value) {
$arr1[$key][] = array_pop($arr[$key]);
}
print_r($arr);
print_r($arr1);
Use array_pop():
http://codepad.org/GeP6OEtf
<?php
$arr=array(
"NAME"=>array('a','b','c','d'),
"DESC"=>array('A','B','C','D')
);
$newarr=array();
foreach ($arr as $key=>$value) {
$newarr[$key]=array(array_pop($arr[$key]));
}
print_r($arr);
echo "\n-------------\n";
print_r($newarr);
You can use extract function.
extract($array);
this will give you two arrays automatically.
reference
I have two same-length arrays like this:
Array
(
[0] => a
[1] => b
[2] => c
)
Array
(
[0] => 1
[1] => 2
[2] => 3
)
And I want to end up with this:
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 2
)
[2] => Array
(
[0] => c
[1] => 3
)
)
array_combine would make one set of the above values into array keys, which I don't want -- I want both to end up as array values, combining each item of the two arrays into a new array.
Is there a built in function to do this or do I have to roll my own?
Try this:
$result = array();
foreach ($array1 as $i => $val) {
$result[] = array($val, $array2[$i]);
}
http://codepad.viper-7.com/Jx5H1Q
Is there a built in function to do this
Yes
or do I have to roll my own?
No
By calling array_map() and feeding it null as the callback parameter, then feeding it 2 or more arrays, it will restructure your data as desired.
Code: (Demo)
$array1 = ['a', 'b', 'c'];
$array2 = [1, 2, 3];
var_export(array_map(null, $array1, $array2));
Output:
array (
0 =>
array (
0 => 'a',
1 => 1,
),
1 =>
array (
0 => 'b',
1 => 2,
),
2 =>
array (
0 => 'c',
1 => 3,
),
)
If you had string keys, you could use array_merge_recursive to merge them. As it is, though, you'll need to do something else. For instance:
$result = Array();
$arrays = Array($array1,$array2...);
foreach($arrays as $arr) {
foreach($arr as $k=>$v) $result[$k][] = $v;
}