Create indexed array of two-element subarrays from flat associative array - php

Is it possible to convert this array:
array(
'A' => 'B',
'C' => 'D',
)
To this array:
array(
array(
'A',
'B',
),
array(
'C',
'D',
),
)

You are probably looking for the array_map (builds pairings based on existing arrays, see Example #4 Creating an array of arrays on the manual page) and the array_keys (all keys of an array) functions:
array_map(null, array_keys($array), $array));

$source = array(
'A' => 'B',
'C' => 'D',
)
foreach ($source as $key => $value){
$result[] = array($key, $value);
}
var_dump($result);

Related

Combine 2 arrays into a third array with inconstant unique keys from one array

I have 2 arrays as below.
$keys = [1,2,3,4-1,99,1,2,3,4-1,4-2,4-3,99,1,2,3,4-1,4-2,99]
$values = [a,b,c,d,x,a1,b1,c1,d1,e,g,x,a2,b2,c2,d2,e,x]
I want to combine into an array like:
$result = array(
[0]=>array(1=>a,2=>b,3=>c,4-1=>d,99=>x),
[1]=>array(1=>a1,2=>b1,3=>c1,4-1=>d1,4-2=>e,4-3=>g,99=>x),
[2]=>array(1=>a2,2=>b2,3=>c2,4-1=>d2,4-2=>e,99=>x
);
The rule is break anytime $key=99.
Currently, I tried to use array_chunk but the syntax only allows me to chunk the array by the number of unique keys, which is not constant in my example.
Any advice?
You need to write a custom script which combines these two arrays by your logic.
You need to fetch each key from the $keys array and combine it with the same element by position from the $values array.
Example:
<?php
$keys = ['1', '2', '3', '4-1', '99', '1', '2', '3', '4-1', '4-2', '4-3', '99', '1', '2', '3', '4-1', '4-2', '99'];
$values = ['a', 'b', 'c', 'd', 'x', 'a1', 'b1', 'c1', 'd1', 'e', 'g', 'x', 'a2', 'b2', 'c2', 'd2', 'e', 'x'];
$i = 0;
$result = [];
foreach ($keys as $index => $key) {
if (empty($result[$i]))
$result[$i] = [$key => $values[$index]];
else
$result[$i][$key] = $values[$index];
if ($key == 99)
++$i;
}
print_r($result);
You can use foreach loop to achieve this
$keys = ["1","2","3","4-1","99","1","2","3","4-1","4-2","4-3","99","1","2","3","4-1","4-2","99"];
$values = ["a","b","c","d","x","a1","b1","c1","d1","e","g","x","a2","b2","c2","d2","e","x"];
$new_array = array();
$split_at = "99";
$i = 0;
foreach ($keys as $key => $value) {
$new_array[$i][$value] =$values[$key];
if($split_at == $value){
$i++;
}
}
print_r($new_array);
DEMO

Recursively Reformat Prefixed Array [duplicate]

This question already has answers here:
How to access and manipulate multi-dimensional array by key names / path?
(10 answers)
Closed 6 years ago.
How can I convert a flat array into a nested array where the nested keys are prefixed with the same value. For example say I have the following array:
[
'name' => 'a',
'content' => 'b',
'author_fullName' => 'c',
'author_email' => 'd',
'author_role_name' => 'e'
]
Then the out of the array would be:
[
'name' => 'a',
'content' => 'b',
'author' => [
'fullName' => 'c',
'email' => 'd',
'role' => [
'name' => 'e'
]
]
]
Ideally I'd like a solution using the built in array functions as I prefer functional syntax rather than using for loops. I'd appreciate the help. Thanks
Try below code:
<?php
$a = [
'name' => 'a',
'content' => 'b',
'author_fullName' => 'c',
'author_email' => 'd',
'author_role_name' => 'e'
];
$finalArray =[];
array_walk($a, function(&$value, $key) use(&$finalArray) {
$indexes = explode('_',$key);
foreach ($indexes as $index){
$finalArray = &$finalArray[$index];
}
$finalArray = $value;
});
print_r($finalArray);
Another solution
$delimiter = '_';
$result = [];
foreach($array as $k => $v)
{
$split = explode($delimiter, $k, 2);//explode only as much as we need
if(count($split) > 1)
{
if(!isset($result[$split[0]]))
{
$result[$split[0]] = [];
}
//this assumes we're not interested in more than two depths
//in tandem with the explode limit
$result[$split[0]][$split[1]] = $v;
}
else
{
$result[$k] = $v;
}
}

PHP - get specific element form each sub array without looping

In php is there a way to get an element from each sub array without having to loop - thinking in terms of efficiency.
Say the following array:
$array = array(
array(
'element1' => a,
'element2' => b
),
array(
'element1' => c,
'element2' => d
)
);
I would like all of the 'element1' values from $array
There are a number of different functions that can operate on arrays for you, depending on the output desired...
$array = array(
array(
'element1' => 'a',
'element2' => 'b'
),
array(
'element1' => 'c',
'element2' => 'd'
)
);
// array of element1s : array('a', 'c')
$element1a = array_map(function($item) { return $item['element1']; }, $array);
// string of element1s : 'ac'
$element1s = array_reduce($array, function($value, $item) { return $value . $item['element1']; }, '');
// echo element1s : echo 'ac'
array_walk($array, function($item) {
echo $item['element1'];
});
// alter array : $array becomes array('a', 'c')
array_walk($array, function(&$item) {
$item = $item['element1'];
});
Useful documentation links:
array_map
array_reduce
array_walk
You can use array_map.
Try code below...
$arr = $array = array(
array(
'element1' => a,
'element2' => b
),
array(
'element1' => c,
'element2' => d
)
);
print_r(array_map("getFunc", $arr));
function getFunc($a)
{
return $a['element1'];
}
See Codepad.
But I think array_map will also use loop internally.
If you're running PHP 5.5 (currently the beta-4 is available), then the following
$element1List = array_column($array, 'element1');
should give $element1List as an simple array of just the element1 values for each element in $array
$array = array(
array(
'element1' => a,
'element2' => b
),
array(
'element1' => c,
'element2' => d
)
);
$element1List = array_column($array, 'element1');
print_r($element1List);
gives
Array
(
[0] => a
[1] => c
)
Without loop? Recursion!
$array = array(
array(
'element1' => 'a',
'element2' => 'b'
),
array(
'element1' => 'c',
'element2' => 'd'
)
);
function getKey($array,$key,$new = array()){
$count = count($array);
$new[] = $array[0][$key];
array_shift($array);
if($count==1)
return $new;
return getKey($array,$key,$new);
}
print_R(getKey($array,'element1'));
As I understood from Wikipedia Recursion is not a loop.

How can I efficiently split an array into its associative key arrays?

How can I split a single array into it's sub-keys?
$arr = array(
0 => array(
'foo' => '1',
'bar' => 'A'
),
1 => array(
'foo' => '2',
'bar' => 'B'
),
2 => array(
'foo' => '3',
'bar' => 'C'
)
);
What is the most efficient way to return an array of foo and bar separately?
I need to get here:
$foo = array('1','2','3');
$bar = array('A','B','C');
I'm hoping there's a clever way to do this using array_map or something similar. Any ideas?
Or do I have to loop through and build each array that way? Something like:
foreach ($arr as $v) {
$foo[] = $v['foo'];
$bar[] = $v['bar'];
}
In a lucky coincidence, I needed to do almost the exact same thing earlier today. You can use array_map() in combination with array_shift():
$foo = array_map('array_shift', &$arr);
$bar = array_map('array_shift', &$arr);
Note that $arr is passed by reference! If you don't do that, then each time it would return the contents of $arr[<index>]['foo']. However, again because of the reference - you won't be able to reuse $arr, so if you need to do that - copy it first.
The downside is that your array keys need to be ordered in the same way as in your example, because array_shift() doesn't actually know what the key is. It will NOT work on the following array:
$arr = array(
0 => array(
'foo' => '1',
'bar' => 'A'
),
1 => array(
'bar' => 'B',
'foo' => '2'
),
2 => array(
'foo' => '3',
'bar' => 'C'
)
);
Update:
After reading the comments, it became evident that my solution triggers E_DEPRECATED warnings for call-time-pass-by-reference. Here's the suggested (and accepted as an answer) alternative by #Baba, which takes advantage of the two needed keys being the first and last elements of the second-dimension arrays:
$foo = array_map('array_shift', $arr);
$bar = array_map('array_pop', $arr);
$n = array();
foreach($arr as $key=>$val) {
foreach($val as $k=>$v) {
$n[$k][] = $v;
}
}
array_merge_recursive will combine scalar values with the same key into an array. e.g.:
array_merge_recursive(array('a',1), array('b',2)) === array(array('a','b'),array(1,2));
You can use this property to simply apply array_merge_recursive over each array in your array as a separate argument:
call_user_func_array('array_merge_recursive', $arr);
You will get this result:
array (
'foo' =>
array (
0 => '1',
1 => '2',
2 => '3',
),
'bar' =>
array (
0 => 'A',
1 => 'B',
2 => 'C',
),
)
It won't even be confused by keys in different order.
However, every merged value must be scalar! Arrays will be merged instead of added as a sub-array:
array_merge_recursive(array(1), array(array(2)) === array(array(1,2))
It does not produce array(array(1, array(2)))!

Drop elements from a array based on another array

$arr1 = array(
'a' => 123,
'b' => 123,
'c' => 123,
'd' => 123,
);
$arr2 = ('a', 'b', 'c', 'd', 'e');
How can I remove elements from $arr2 that don't exist as keys in $arr1 ?
for example e doesn't exist as key in $arr1 so it should be removed
$arr2 = array_intersect($arr2, array_keys($arr1))
it computes intersection of two sets - $arr2 values and $arr1 keys
Try this:
foreach ( $arr2 as $key => $value ) {
if ( !array_key_exists( $value, $arr1 ) ) {
unset( $arr2[$key] );
}
}
Why not use the simple approach and use array_keys? This avoids having to perform an operation for each key by getting ALL of the keys at once.
$arr2 = array_keys($arr1);

Categories