This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
Having an associative array like
$myarray = array (
'user' => array (
2 => 'john',
5 => 'done',
21 => 'foo'
),
'city' => array (
2 => 'london',
5 => 'buenos aires',
21 => 'paris',
),
'age' => array (
2 => 24,
5 => 38,
21 => 16
)
...
);
EDITED
Assuming I don't know how many keys this array has, nor the keys themselves (they could be whatever) The above is just an example
Is there any elegant way (using built-in functions and not loops) to convert it into
$result = array(
array(
'user',
'city',
'age'
...
),
array(
'john',
'london',
24
...
),
array(
'done',
'buenos aires',
38
...
),
array(
'foo',
'paris',
16
...
)
);
As a side question: how to obtain this too (in a similar elegant way)
$result = array(
array(
'row',
'user',
'city',
'age'
...
),
array(
2,
'john',
'london',
24
...
),
array(
5,
'done',
'buenos aires',
38
...
),
array(
21,
'foo',
'paris',
16
...
)
);
Note that both of these operations are basically the transpose of your original array.
All of this is strongly adapted from this answer (consider upvoting it!).
helper
First we need a helper function, which keeps the row headers as the keys in the associative array:
function flipArrayKeys($arr) {
$out = array('row' => array_keys($arr));
foreach ($arr as $key => $subarr) {
foreach ($subarr as $subkey => $subvalue) {
$out[$subkey][] = $subvalue;
}
}
return $out;
}
flipArrayKeys($myarray) gives:
array (
'row' =>
array (
0 => 'user',
1 => 'city',
2 => 'age',
),
2 =>
array (
0 => 'john',
1 => 'london',
2 => 24,
),
5 =>
array (
0 => 'done',
1 => 'buenos aires',
2 => 38,
),
21 =>
array (
0 => 'foo',
1 => 'paris',
2 => 16,
),
)
part 1
$result = array_values(flipArrayKeys($myarray));
and now result looks like:
array (
0 =>
array (
0 => 'user',
1 => 'city',
2 => 'age',
),
1 =>
array (
0 => 'john',
1 => 'london',
2 => 24,
),
2 =>
array (
0 => 'done',
1 => 'buenos aires',
2 => 38,
),
3 =>
array (
0 => 'foo',
1 => 'paris',
2 => 16,
),
)
This part can also be done using transpose from this answer:
$result = transpose($myarray);
array_unshift($result, array_keys($myarray));
part 2
function flipArrayWithHeadings($arr) {
$out = flipArrayKeys($arr);
foreach (array_keys($out) as $key) {
array_unshift($out[$key],$key);
}
return array_values($out);
}
So flipArrayWithHeadings($myarray) looks like:
array (
0 =>
array (
0 => 'row',
1 => 'user',
2 => 'city',
3 => 'age',
),
1 =>
array (
0 => 2,
1 => 'john',
2 => 'london',
3 => 24,
),
2 =>
array (
0 => 5,
1 => 'done',
2 => 'buenos aires',
3 => 38,
),
3 =>
array (
0 => 21,
1 => 'foo',
2 => 'paris',
3 => 16,
),
)
Use the array_values function as:
$result = array(array_values($myarray['user']),
array_values($myarray['city']),
array_values($myarray['age']));
For the 2nd part of the question you can do:
$result2 = array_keys($myarray);
foreach(array_keys($myarray['user']) as $k) {
$result2[] = array($k, $myarray['user'][$k], $myarray['city'][$k], $myarray['age'][$k]);
}
Related
This question already has answers here:
Sort multidimensional array based on another array [duplicate]
(3 answers)
Closed 26 days ago.
Hi I have an array that looks like this
array[
0 => array[
'id' => 1,
'name' => 'Test 1'
'classId' => 3
],
1 => array[
'id' => 1,
'name' => 'Test 1'
'classId' => 15
],
2 => array[
'id' => 1,
'name' => 'Test 1'
'classId' => 17
],
]
And I have another array that contains classIds like:
classIds = [15, 17, 3]
And I want to sort my array based on classIds
I can do a a double loop to compare it. I am just wondering is there anyother way to get it done?
Actually one loop i enough:
<?php
$order = [15, 17, 3];
$input = [
[
'id' => 1,
'name' => 'Test 1',
'classId' => 3,
],
[
'id' => 1,
'name' => 'Test 1',
'classId' => 15,
],
[
'id' => 1,
'name' => 'Test 1',
'classId' => 17,
],
];
$output = [];
array_walk($input, function($entry) use ($order, &$output) {
$output[array_search($entry['classId'], $order)] = $entry;
});
ksort($output);
print_r($output);
In case you consider array_search(...) also a "loop" (though it internally works different), that would be an alternative which produces the same output:
<?php
$order = array_flip([15, 17, 3]);
$input = array_values([
[
'id' => 1,
'name' => 'Test 1',
'classId' => 3,
],
[
'id' => 1,
'name' => 'Test 1',
'classId' => 15,
],
[
'id' => 1,
'name' => 'Test 1',
'classId' => 17,
],
]);
$output = [];
array_walk($input, function($entry, $index) use ($order, &$output) {
$output[$order[$entry['classId']]] = $entry;
});
ksort($output);
print_r($output);
The output of both approaches is:
Array
(
[0] => Array
(
[id] => 1
[name] => Test 1
[classId] => 15
)
[1] => Array
(
[id] => 1
[name] => Test 1
[classId] => 17
)
[2] => Array
(
[id] => 1
[name] => Test 1
[classId] => 3
)
)
You can sort the array directly and in-place using usort and an anonymous comparison function that retrieves the target indices from $classIds.
Given
<?php
$arr = array(
0 => array(
'id' => 1,
'name' => 'Test 1',
'classId' => 3
),
1 => array(
'id' => 1,
'name' => 'Test 1',
'classId' => 15
),
2 => array(
'id' => 1,
'name' => 'Test 1',
'classId' => 17
),
);
$classIds = [15, 17, 3];
you can sort $arr with
// Create assoc array mapping classIds to their desired sorted position.
$classIdsOrder = array_combine($classIds, range(0, count($classIds)-1));
// Sort $arr according to the 'classId' order described by $classIdsOrder
usort($arr, function ($left, $right) use ($classIdsOrder) {
return $classIdsOrder[$left['classId']] <=> $classIdsOrder[$right['classId']];
});
print_r($arr);
which outputs
Array
(
[0] => Array
(
[id] => 1
[name] => Test 1
[classId] => 15
)
[1] => Array
(
[id] => 1
[name] => Test 1
[classId] => 17
)
[2] => Array
(
[id] => 1
[name] => Test 1
[classId] => 3
)
)
Try it online!
I got 2 arrays. In first one field number is empty:
array (
3 => array ( 0 => array ( 'id' => 1, 'number' => 0, 'time' => 40,), ),
4 => array ( 0 => array ( 'id' => 2, 'number' => 0, 'time' => 40, ), ),
5 => array ( 0 => array ( 'id' => 3, 'number' => 0, 'time' => 40, ), ),
6 => array ( 0 => array ( 'id' => 1, 'number' => 0, 'time' => 41, ), ),
7 => array ( 0 => array ( 'id' => 2, 'number' => 0, 'time' => 41, ), ),
8 => array ( 0 => array ( 'id' => 3, 'number' => 0, 'time' => 41, ), ),
)
In the second one fields number are not empty, however the array is bit different, because it doesn't have a 2 arrays in the middle (id = 3, time = 40 and id = 3, time = 41).
array ( 3 => array ( 'id' => '1', 'number' => '3785', 'time' => '40', ),
4 => array ( 'id' => '2', 'number' => '1574', 'time' => '40', ),
5 => array ( 'id' => '1', 'number' => '2954', 'time' => '41', ),
6 => array ( 'id' => '2', 'number' => '2463', 'time' => '41', ),
)
What I want to do is to some sort of merge of this arrays into one looking like this:
array (
3 => array ( 'id' => '1', 'number' => '3785', 'time' => '40', ),
4 => array ( 'id' => '2', 'number' => '1574', 'time' => '40', ),
5 => array ( 0 => array ( 'id' => 3, 'number' => 0, 'time' => 40, ), ),
6 => array ( 'id' => '1', 'number' => '2954', 'time' => '41', ),
7 => array ( 'id' => '2', 'number' => '2463', 'time' => '41', ),
8 => array ( 0 => array ( 'id' => 3, 'number' => 0, 'time' => 41,), ),
)
I tried some variations of array_merge() and array_combine(), but neither of them seems to work, or perhaps I've been using them badly.
Again, notice how row 5 and 8 are not affected because (id = 3 and time = 40) and (id = 3 and time = 41), respectively, are not represented in the second array.
What I tried and it works, but it doesn't look well in my opinion:
foreach($arr2 as $wpis2){
foreach($arr as $key=>$wpis){
if($wpis2['id'] == $wpis[0]['id'] && $wpis2['time'] == $wpis[0]['time']){
$arr[$key] = $wpis2;
}
}
}
You will need to iterate over the first array in order to populate a key-map based on the combination of id and time values from all rows.
Use a second loop to iterate over the second array and access the correct key to overwrite by leveraging the mapping array.
Code: (Demo)
$map = [];
foreach ($first as $k => [['id' => $id, 'time' => $time]]) {
$map["{$id}_{$time}"] = $k;
}
foreach ($second as $row) {
$key = $map["{$row['id']}_{$row['time']}"];
$first[$key] = $row;
}
var_export($first);
I have 2 arrays one contains just a list of email address and the other contains emails and names.
The list of emails in array1 are stored in a database and the other array is a list of new and current users.
I have tried using array_diff however this only seems to work if I specify in my loop that I just want emails.
$array1 = array(
0 => 'dave#daveshouse.com',
1 => 'sam#samshouse.com',
2 => 'jim#jimshouse.com',
3 => 'olly#ollyshouse.com',
4 => 'tom#tomshouse.com'
);
$array2 = array(
0 => array(
0 => 'tom',
1 => 'tom#tomshouse.com'
),
1 => array(
0 => 'james',
1 => 'james#jameshouse.com'
),
2 => array(
0 => 'marvin',
1 => 'marvin#marvinshouse.com'
),
3 => array(
0 => 'jane',
1 => 'jane#janeshouse.com'
),
);
$array2emails = array();
foreach ($array2 as $item) {
$array2emails[] = $item[1];
}
$result = array_diff($array2emails, $array1);
$results gives me
Array
(
[1] => james#jameshouse.com
[2] => marvin#marvinshouse.com
[3] => jane#janeshouse.com
)
however I need to get this:
Array
(
[1] => array(
[0] => james
[1] => james#jameshouse.com
)
[2] => array(
[0] => marvin
[1] => marvin#marvinshouse.com
)
[3] => array(
[0] => jane
[1] => jane#janeshouse.com
)
)
Any help would be much appreciated. Thanks
Since the array returned by array_diff has the same keys as the original array, you can use that to get the elements of the original array back, with array_intersect_key.
$array1 = array(
0 => 'dave#daveshouse.com',
1 => 'sam#samshouse.com',
2 => 'jim#jimshouse.com',
3 => 'olly#ollyshouse.com',
4 => 'tom#tomshouse.com'
);
$array2 = array(
0 => array(
0 => 'tom',
1 => 'tom#tomshouse.com'
),
1 => array(
0 => 'james',
1 => 'james#jameshouse.com'
),
2 => array(
0 => 'marvin',
1 => 'marvin#marvinshouse.com'
),
3 => array(
0 => 'jane',
1 => 'jane#janeshouse.com'
),
);
$array2emails = array_column($array2, 1);
$keys = array_diff($array2emails, $array1);
$result = array_intersect_key($array2, $keys);
print_r($result);
Result:
Array
(
[1] => Array
(
[0] => james
[1] => james#jameshouse.com
)
[2] => Array
(
[0] => marvin
[1] => marvin#marvinshouse.com
)
[3] => Array
(
[0] => jane
[1] => jane#janeshouse.com
)
)
$array1 = array(
0 => 'dave#daveshouse.com',
1 => 'sam#samshouse.com',
2 => 'jim#jimshouse.com',
3 => 'olly#ollyshouse.com',
4 => 'tom#tomshouse.com'
);
$array2 = array(
0 => array(
0 => 'tom',
1 => 'tom#tomshouse.com'
),
1 => array(
0 => 'james',
1 => 'james#jameshouse.com'
),
2 => array(
0 => 'marvin',
1 => 'marvin#marvinshouse.com'
),
3 => array(
0 => 'jane',
1 => 'jane#janeshouse.com'
),
);
$diffs = array();
foreach ($array2 as $item) {
if (!in_array($item[1], $array1)) {
$diffs[] = $item;
}
}
Since you are using a foreach loop why not create the array there?
As long as the arrays are not to long this will word nicely. I even took the original key into the new array. So you will be able to do other comparison methods to it.
$array1 = [
0 => 'dave#daveshouse.com',
1 => 'sam#samshouse.com',
2 => 'jim#jimshouse.com',
3 => 'olly#ollyshouse.com',
4 => 'tom#tomshouse.com'
];
$array2 = [
0 => [
0 => 'tom',
1 => 'tom#tomshouse.com'
],
1 => [
0 => 'james',
1 => 'james#jameshouse.com'
],
2 => [
0 => 'marvin',
1 => 'marvin#marvinshouse.com'
],
3 => [
0 => 'jane',
1 => 'jane#janeshouse.com'
],
];
$arrayExits = [];
foreach ($array2 as $key => $item) {
if(in_array($item[1], $array1)) {
$arrayExits[$key] = $item;
}
}
print_r($arrayExits);
Use array_filter function.
function filterEmail($value, $key){
global $array1;
return !in_array($value[1], $array1);
}
$emailDiff = array_filter($array2, 'filterEmail' , ARRAY_FILTER_USE_BOTH );
print_r($emailDiff );
This is my array:
$arr = array(
0 => array(
'title' => 'test1',
'count' => 4,
'month' => 'jan-2015'
),
1 => array(
'title' => 'test2',
'count' => 10,
'month' => 'jan-2015'
),
2 => array(
'title' => 'test3',
'count' => 14,
'month' => 'jun-2015'
),
3 => array(
'title' => 'test4',
'count' => 45,
'month' => 'july-2015'
),
);
I've to convert this array into multi-dimentional array as below:
$arr = array(
'jan-2015' => array(
0 => array(
'title' => 'test1',
'count' => 4,
),
1 => array(
'title' => 'test2',
'count' => 10,
),
),
'jun-2015' => array(
0 => array(
'title' => 'test3',
'count' => 14,
),
),
'july-2015' => array(
0 => array(
'title' => 'test4',
'count' => 45,
),
),
);
I've tried to make it as expected but unfortunately i can't make this.
Is any other solutions for this?
According to your data structure :
$arr = array(
0 => array(
'title' => 'test1',
'count' => 4,
'month' => 'jan-2015'
),
1 => array(
'title' => 'test2',
'count' => 10,
'month' => 'jan-2015'
),
2 => array(
'title' => 'test3',
'count' => 14,
'month' => 'jun-2015'
),
3 => array(
'title' => 'test4',
'count' => 45,
'month' => 'july-2015'
),
);
try this:
$newArray = array();
foreach($arr as $key => $val) {
$newArray[$val['month']][] = $val;
}
echo '<pre>'.print_r($newArray,1).'</pre>';
Output:
Array
(
[jan-2015] => Array
(
[0] => Array
(
[title] => test1
[count] => 4
[month] => jan-2015
)
[1] => Array
(
[title] => test2
[count] => 10
[month] => jan-2015
)
)
[jun-2015] => Array
(
[0] => Array
(
[title] => test3
[count] => 14
[month] => jun-2015
)
)
[july-2015] => Array
(
[0] => Array
(
[title] => test4
[count] => 45
[month] => july-2015
)
)
)
You could use this function:
function transform($input) {
// Extract months, and use them as keys, with value set to empty array
// The array_fill_keys also removes duilicates
$output = array_fill_keys(array_column($input, 'month'), array());
foreach ($input as $element) {
$copy = $element;
// remove the month key
unset($copy["month"]);
// assign this to the month key in the output
$output[$element["month"]][] = $copy;
}
return $output;
}
Call it like this:
$arr = array(
0 => array(
'title' => 'test1',
'count' => 4,
'month' => 'jan-2015'
),
1 => array(
'title' => 'test2',
'count' => 10,
'month' => 'jan-2015'
),
2 => array(
'title' => 'test3',
'count' => 14,
'month' => 'jun-2015'
),
3 => array(
'title' => 'test4',
'count' => 45,
'month' => 'july-2015'
),
);
print_r (transform($arr));
Output:
Array
(
[jan-2015] => Array
(
[0] => Array
(
[title] => test1
[count] => 4
)
[1] => Array
(
[title] => test2
[count] => 10
)
)
[jun-2015] => Array
(
[0] => Array
(
[title] => test3
[count] => 14
)
)
[july-2015] => Array
(
[0] => Array
(
[title] => test4
[count] => 45
)
)
)
By using answer of #Girish Patidar, You can achieve this by:
$outputArr = array();
$to_skip = array();
foreach($arr as $row){
$to_skip = $row;
unset($to_skip['month']);
$outputArr[$row['month']][] = $to_skip;
}
echo "<pre>";
print_r($outputArr);
die;
There could many way to do this. Please try this one if it works for you
<?php
$newArr=NULL;
foreach($arr as $array)
{
$temp=NULL;
$temp['title']=$array['title'];
$temp['count']=$array['count'];
$newArr[$array['month']][]=$temp;
}
var_dump($newArr);
?>
I have the following array which I am getting as mysql result set
Array
(
[0] => Array
(
[slug] => block_three_column
[title] => CSG 2
[type_id] => 8
[entry_id] => 6
[stream_id] => 11
)
[1] => Array
(
[slug] => block_three_column
[title] => CSG
[type_id] => 8
[entry_id] => 5
[stream_id] => 11
)
)
Array
(
[0] => Array
(
[slug] => block_three_column
[title] => CSG 2
[type_id] => 8
[entry_id] => 6
[stream_id] => 11
)
[1] => Array
(
[slug] => block_three_column
[title] => CSG
[type_id] => 8
[entry_id] => 5
[stream_id] => 11
)
)
The both arrays are similar I want get the unique entry id using php.
I tried with the following code but it is producing 2 arrays again.
foreach($block_results as $rowarr)
{
foreach($rowarr as $k=>$v)
{
if($k == "entry_id")
{
$entid[] = $v;
}
}
}
Any help is highly appreciated. Thanks in advance.
You can use array_map() instead of foreach(). Example:
$entry_ids = array_unique(
array_map(
function($v){
return $v['entry_id'];
},
$array
)
);
var_dump($entry_ids);
array_unique() is to remove duplicate elements from array().
You can get the entry_id directly:
$array = array(
array(
'slug' => 'block_three_column',
'title' => 'CSG 2',
'type_id' => 8,
'entry_id' => 6,
'stream_id' => 11
),
array(
'slug' => 'block_three_column',
'title' => 'CSG',
'type_id' => 8,
'entry_id' => 5,
'stream_id' => 11
)
);
foreach ($array as $innerArray) {
if (isset($innerArray['entry_id'])) {
$entid[] = $innerArray['entry_id'];
}
}
var_dump($entid);
Output is:
array
0 => int 6
1 => int 5
Assuming that you want a list of the unique values of entry_id from the array, and it is possible that some will not have an entry_id set:
$entid = array();
foreach ( $array as $blockArray) {
if ( isset( $blockArray['entry_id'] )
&& !in_array( $blockArray['entry_id'], $entid ) ) {
$entid[] = $blockArray['entry_id'];
}
}
var_dump( $entid );
Try this:
PHP
$entid = array(); //Holds unique id's
foreach($block_results as $rowarr)
{
//Make sure entry_id exists
$entid[] = array_key_exists('entry_id',$rowarry) ? $rowarr['entry_id'] : false;
}
If they are always similiar and the same length:
foreach ($array1 as $key => $value) {
$firstValue = $array1[$key]['entry_id'];
$secondValue = $array2[$key]['entry_id'];
}
Though, keep in mind this solution is very sensitive to errors.
try this like your code:
$block_results = array(
array(
'slug' => 'block_three_column',
'title' => 'CSG 2',
'type_id' => 8,
'entry_id' => 6,
'stream_id' => 11
),
array(
'slug' => 'block_three_column',
'title' => 'CSG',
'type_id' => 8,
'entry_id' => 6,
'stream_id' => 11
),
array(
'slug' => 'block_three_column',
'title' => 'CSG',
'type_id' => 8,
'entry_id' => 7,
'stream_id' => 11
)
);
var_dump($block_results);
$entid=array();
if(count($block_results)>0)foreach($block_results as $rowarr)
{
$entid[] = $rowarr['entry_id'];
}
$entid=array_unique($entid);
var_dump($entid);
output:
array
0 =>
array
'slug' => string 'block_three_column' (length=18)
'title' => string 'CSG 2' (length=5)
'type_id' => int 8
'entry_id' => int 6
'stream_id' => int 11
1 =>
array
'slug' => string 'block_three_column' (length=18)
'title' => string 'CSG' (length=3)
'type_id' => int 8
'entry_id' => int 6
'stream_id' => int 11
2 =>
array
'slug' => string 'block_three_column' (length=18)
'title' => string 'CSG' (length=3)
'type_id' => int 8
'entry_id' => int 7
'stream_id' => int 11
array
0 => int 6
2 => int 7