PHP - Order array associative by specific value - php

I'm looking for a way to order an array associative by a specific value, I'm not sure if it's possible. I tried it with array_multisort() and usort() functions, but I'm afraid that I can not get it.
Example:
$array[] = array('id' => 74215, 'type' => 'BOX');
$array[] = array('id' => 76123, 'type' => 'UNT');
$array[] = array('id' => 71231, 'type' => '');
$array[] = array('id' => 79765, 'type' => 'UNT');
$array[] = array('id' => 77421, 'type' => 'BOX');
If I want to order by 'BOX', then the array will be:
Array (
[0] => Array
(
[id] => 77421
[type] => 'BOX'
)
[1] => Array
(
[id] => 74215
[type] => 'BOX'
)
[2] => Array
(
[id] => 76123
[type] => 'UNT'
)
.
.
.
I could pass other string like 'UNT', and order by like that.
Is this possible??

I assume you want to "sort" by string match, first all those who match that string, after that all those that don't. Unless you have an archaic php version, this could work:
$sortvalue = 'BOX';
usort($array, function($a, $b) use ($sortvalue) {
if($a['type'] == $sortvalue) return -1;
elseif($b['type'] == $sortvalue) return 1;
else return 0;
});
this should put any 'BOX' entry to the front of your array.
If all others shall be grouped, instead of return 0 do return $a['type'] < $b['type'].
edit: integrated kamal pal's suggestion/correction

I'm not sure if PHP has it's own function that does that, but i write my own, hope it helps:
function sortArray($array_x, $key)
{
$added_indexes;
$new_array;
for($i=0;$i<count($array_x);$i++)
{
if($array_x[$i]['type']==$key){
$new_array[]=$array_x[$i];
$added_indexes[]=$i;
}
}
for($i=0;$i<count($array_x);$i++)
{
if(!in_array($i,$added_indexes))
{
$new_array[]=$array_x[$i];
}
}
return $new_array;
}
So when you do this:
$array[] = array('id' => 74215, 'type' => 'BOX');
$array[] = array('id' => 76123, 'type' => 'UNT');
$array[] = array('id' => 71231, 'type' => '');
$array[] = array('id' => 79765, 'type' => 'UNT');
$array[] = array('id' => 77421, 'type' => 'BOX');
print_r(sortArray($array,"BOX"));
Gives this:
Array
(
[0] => Array
(
[id] => 74215
[type] => BOX
)
[1] => Array
(
[id] => 77421
[type] => BOX
)
[2] => Array
(
[id] => 76123
[type] => UNT
)
[3] => Array
(
[id] => 71231
[type] =>
)
[4] => Array
(
[id] => 79765
[type] => UNT
)
)

Yeah I was thinking in a similar solution:
usort($array, function ($a, $b) {
return $a['type'] == 'BOX' ? -1 : ($b['type'] == 'BOX' ? 1 : 0);
});

Related

Summation of array elements by the indexer [duplicate]

I have an array of subarrays in the following format:
[
'a' => ['id' => 20, 'name' => 'chimpanzee'],
'b' => ['id' => 40, 'name' => 'meeting'],
'c' => ['id' => 20, 'name' => 'dynasty'],
'd' => ['id' => 50, 'name' => 'chocolate'],
'e' => ['id' => 10, 'name' => 'bananas'],
'f' => ['id' => 50, 'name' => 'fantasy'],
'g' => ['id' => 50, 'name' => 'football']
]
And I would like to group it into a new array based on the id field in each subarray.
array
(
10 => array
(
e => array ( id = 10, name = bananas )
)
20 => array
(
a => array ( id = 20, name = chimpanzee )
c => array ( id = 20, name = dynasty )
)
40 => array
(
b => array ( id = 40, name = meeting )
)
50 => array
(
d => array ( id = 50, name = chocolate )
f => array ( id = 50, name = fantasy )
g => array ( id = 50, name = football )
)
)
$arr = array();
foreach ($old_arr as $key => $item) {
$arr[$item['id']][$key] = $item;
}
ksort($arr, SORT_NUMERIC);
foreach($array as $key => $value){
$newarray[$value['id']][$key] = $value;
}
var_dump($newarray);
piece of cake ;)
The following code adapts #Tim Cooper’s code to mitigate Undefined index: id errors in the event that one of the inner arrays doesn’t contain an id:
$arr = array();
foreach($old_arr as $key => $item)
{
if(array_key_exists('id', $item))
$arr[$item['id']][$key] = $item;
}
ksort($arr, SORT_NUMERIC);
However, it will drop inner arrays without an id.
E.g.
$old_arr = array(
'a' => array ( 'id' => 20, 'name' => 'chimpanzee' ),
'b' => array ( 'id' => 40, 'name' => 'meeting' ),
'c' => array ( 'id' => 20, 'name' => 'dynasty' ),
'd' => array ( 'id' => 50, 'name' => 'chocolate' ),
'e' => array ( 'id' => 10, 'name' => 'bananas' ),
'f' => array ( 'id' => 50, 'name' => 'fantasy' ),
'g' => array ( 'id' => 50, 'name' => 'football' ),
'h' => array ( 'name' => 'bob' )
);
will drop the 'h' array completely.
You can also use Arrays::groupBy() from ouzo-goodies:
$groupBy = Arrays::groupBy($array, Functions::extract()->id);
print_r($groupBy);
And result:
Array
(
[20] => Array
(
[0] => Array
(
[id] => 20
[name] => chimpanzee
)
[1] => Array
(
[id] => 20
[name] => dynasty
)
)
[40] => Array
(
[0] => Array
(
[id] => 40
[name] => meeting
)
)
[50] => Array
(
[0] => Array
(
[id] => 50
[name] => chocolate
)
[1] => Array
(
[id] => 50
[name] => fantasy
)
[2] => Array
(
[id] => 50
[name] => football
)
)
[10] => Array
(
[0] => Array
(
[id] => 10
[name] => bananas
)
)
)
And here are the docs for Arrays and Functions.
Here is a function that will take an array as the first argument and a criteria (a string or callback function) as the second argument. The function returns a new array that groups the array as asked for.
/**
* Group items from an array together by some criteria or value.
*
* #param $arr array The array to group items from
* #param $criteria string|callable The key to group by or a function the returns a key to group by.
* #return array
*
*/
function groupBy($arr, $criteria): array
{
return array_reduce($arr, function($accumulator, $item) use ($criteria) {
$key = (is_callable($criteria)) ? $criteria($item) : $item[$criteria];
if (!array_key_exists($key, $accumulator)) {
$accumulator[$key] = [];
}
array_push($accumulator[$key], $item);
return $accumulator;
}, []);
}
Here is the given array:
$arr = array(
'a' => array ( 'id' => 20, 'name' => 'chimpanzee' ),
'b' => array ( 'id' => 40, 'name' => 'meeting' ),
'c' => array ( 'id' => 20, 'name' => 'dynasty' ),
'd' => array ( 'id' => 50, 'name' => 'chocolate' ),
'e' => array ( 'id' => 10, 'name' => 'bananas' ),
'f' => array ( 'id' => 50, 'name' => 'fantasy' ),
'g' => array ( 'id' => 50, 'name' => 'football' )
);
And examples using the function with a string and a callback function:
$q = groupBy($arr, 'id');
print_r($q);
$r = groupBy($arr, function($item) {
return $item['id'];
});
print_r($r);
The results are the same in both examples:
Array
(
[20] => Array
(
[0] => Array
(
[id] => 20
[name] => chimpanzee
)
[1] => Array
(
[id] => 20
[name] => dynasty
)
)
[40] => Array
(
[0] => Array
(
[id] => 40
[name] => meeting
)
)
[50] => Array
(
[0] => Array
(
[id] => 50
[name] => chocolate
)
[1] => Array
(
[id] => 50
[name] => fantasy
)
[2] => Array
(
[id] => 50
[name] => football
)
)
[10] => Array
(
[0] => Array
(
[id] => 10
[name] => bananas
)
)
)
Passing the callback is overkill in the example above, but using the callback finds its use when you pass in an array of objects, a multidimensional array, or have some arbitrary thing you want to group by.
Maybe it's worth to mention that you can also use php array_reduce function
$items = [
['id' => 20, 'name' => 'chimpanzee'],
['id' => 40, 'name' => 'meeting'],
['id' => 20, 'name' => 'dynasty'],
['id' => 50, 'name' => 'chocolate'],
['id' => 10, 'name' => 'bananas'],
['id' => 50, 'name' => 'fantasy'],
['id' => 50, 'name' => 'football'],
];
// Grouping
$groupedItems = array_reduce($items, function ($carry, $item) {
$carry[$item['id']][] = $item;
return $carry;
}, []);
// Sorting
ksort($groupedItems, SORT_NUMERIC);
print_r($groupedItems);
https://www.php.net/manual/en/function.array-reduce.php
Because of how PHP's sorting algorithm treats multidimensional arrays -- it sorts by size, then compares elements one at a time, you can actually use a key-preserving sort on the input BEFORE restructuring. In functional style programming, this means that you don't need to declare the result array as a variable.
Code: (Demo)
asort($array);
var_export(
array_reduce(
array_keys($array),
function($result, $k) use ($array) {
$result[$array[$k]['id']][$k] = $array[$k];
return $result;
}
)
);
I must say that functional programming is not very attractive for this task because the first level keys must be preserved.
Although array_walk() is more succinct, it still requires the result array to be passed into the closure as a reference variable. (Demo)
asort($array);
$result = [];
array_walk(
$array,
function($row, $k) use (&$result) {
$result[$row['id']][$k] = $row;
}
);
var_export($result);
I'd probably recommend a classic loop for this task. The only thing the loop needs to do is rearrange the first and second level keys. (Demo)
asort($array);
$result = [];
foreach ($array as $k => $row) {
$result[$row['id']][$k] = $row;
}
var_export($result);
To be completely honest, I expect that ksort() will be more efficient than pre-loop sorting, but I wanted to a viable alternative.

Convert 2d array by specified 2d format

I need to convert the below 2d array in to specified 2d array format. Array contains multiple parent and multiple child array. Also, have tried to convert the code, but am not getting the expected output.
This is the code what i have tried,
$a1 = array(
'0' =>
array(
'banner_details' =>
array(
'id' => 2,
'section_id' => 24
),
'slide_details' =>
array(
0 => array(
'id' => 74,
'name' => 'Ads1'
),
1 => array(
'id' => 2,
'name' => 'Ads2'
)
)
),
'1' =>
array(
'banner_details' =>
array(
'id' => 106,
'section_id' => 92
),
'slide_details' =>
array(
0 => array(
'id' => 2001,
'name' => 'Adv1'
),
1 => array(
'id' => 2002,
'name' => 'Adv2'
)
)
)
);
$s = [];
for($i = 0; $i<2; $i++) {
foreach($a1[$i]['slide_details'] as $vs){
$s[] = $vs;
}
}
My output:
Array
(
[0] => Array
(
[id] => 74
[name] => Ads1
)
[1] => Array
(
[id] => 2
[name] => Ads2
)
[2] => Array
(
[id] => 2001
[name] => Adv1
)
[3] => Array
(
[id] => 2002
[name] => Adv2
)
)
Expected output:
Array
(
[24] => Array
(
[0] => 74
[1] => 2
)
[92] => Array
(
[0] => 2001
[1] => 2002
)
)
please check the above code and let me know.
Thanks,
You can apply next simple foreach loop with help of isset() function:
foreach($a1 as $data){
if (isset($data['banner_details']['section_id'])){
$s[$data['banner_details']['section_id']] = [];
if (isset($data['slide_details'])){
foreach($data['slide_details'] as $row){
$s[$data['banner_details']['section_id']][] = $row['id'];
}
}
}
}
Demo
If you know that indexes like banner_details or slide_details or section_id will be there always then you can skip isset() in if statements.
You can use array_column function for simple solution:
$result = [];
foreach ($a1 as $item)
{
$result[$item['banner_details']['section_id']] = array_column($item['slide_details'], 'id');
}
var_dump($result);

PHP sort array using specific letter

I have an php array like below:
Array (
[0] => Array ( [value] => 5 [label] => Akon )
[1] => Array ( [value] => 6 [label] => Angel )
[2] => Array ( [value] => 7 [label] => Britny )
[3] => Array ( [value] => 9 [label] => Mark Anthony )
[4] => Array ( [value] => 8 [label] => Michel )
[5] => Array ( [value] => 4 [label] => Shaggy )
[6] => Array ( [value] => 3 [label] => Smith )
)
I need this array sort by specific letter. For example, if I sort by this "M" letter array should look like below.
Array (
[3] => Array ( [value] => 9 [label] => Mark Anthony )
[4] => Array ( [value] => 8 [label] => Michel )
[6] => Array ( [value] => 3 [label] => Smith )
[0] => Array ( [value] => 5 [label] => Akon )
[1] => Array ( [value] => 6 [label] => Angel )
[2] => Array ( [value] => 7 [label] => Britny )
[5] => Array ( [value] => 4 [label] => Shaggy )
)
The begging letter should comes to first of array.(here begin with m)
I greatly appreciated your any kind of help. Thank you very much...
Your comparison logic is going to be like this:
if two strings A and B start with the same letter, compare them as usual
if A starts with 'M', A wins
if B starts with 'M', B wins
otherwise, compare as usual
in code
$strings = array('Foo', 'Moo', 'Xuux', 'Me', 'Blah', 'Ma');
$letter = 'M';
usort($strings, function($a, $b) use($letter) {
if($a[0] != $b[0]) {
if($a[0] == $letter) return -1;
if($b[0] == $letter) return +1;
}
return strcmp($a, $b);
});
print_r($strings);
class Cmp {
public $letter;
function __construct( $letter ) { $this->letter = $letter; }
function doCmp( $a, $b ) {
if( $a['label'][0] == $this->letter ) {
if( $b['label'][0] != $this->letter ) return -1;
} else {
if( $b['label'][0] == $this->letter ) return 1;
}
return $a['label'] > $b['label'] ? 1 : -1;
}
}
usort( $arr, array( new Cmp( 'M' ), 'doCmp' ) );
$strings = array (
array ( 'value' => 5, 'label' => 'Akon' ),
array ( 'value' => 6, 'label' => 'Angel' ),
array ( 'value' => 7, 'label' => 'Britny' ),
array ( 'value' => 9, 'label' => 'Mark Anthony' ) ,
array ( 'value' => 8, 'label' => 'Michel' ) ,
array ( 'value' => 4, 'label' => 'Shaggy' ) ,
array ( 'value' => 3, 'label' => 'Smith' )
) ;
var_dump($strings);
$letter = 'm';
usort ($strings, function ($left, $right) {
return ((($posLeft = strpos(strtolower($left['label']), 'm')) === false)
? PHP_INT_MAX
: $posLeft)
- ((($posRight = strpos(strtolower($right['label']), 'm')) === false)
? PHP_INT_MAX
: $posRight);
});
var_dump($strings);
Just compares the position of the letter within the two strings. If the letter is not within one of the strings (strpos() returns false), it assumes an "infinite" index (PHP_INT_MAX),
this is an example i found on php.net that could help you and maintain the index : http://www.php.net/manual/en/function.sort.php#99419
Sort the data by the value based on the comparison reflecting the letter (Demo):
<?php
# the data
$data = array(
0 => array(
'value' => 5,
'label' => 'Akon',
),
1 => array(
'value' => 6,
'label' => 'Angel',
),
2 => array(
'value' => 7,
'label' => 'Britny',
),
3 => array(
'value' => 9,
'label' => 'Mark Anthony',
),
4 => array(
'value' => 8,
'label' => 'Michel',
),
5 => array(
'value' => 4,
'label' => 'Shaggy',
),
6 => array(
'value' => 3,
'label' => 'Smith',
),
);
# the letter
$letter = 'M';
# the value to compare against
$value = function(array $a)
{
$key = 'label';
if (!array_key_exists($key, $a))
{
throw new InvalidArgumentException(sprintf('Key "%s" missing.', $key));
}
return $a[$key];
};
# the comparison
$compare = function($a, $b) use ($letter, $value)
{
$a = $value($a);
$b = $value($b);
if($a[0] != $b[0]) {
if($a[0] === $letter) return -1;
if($b[0] === $letter) return +1;
}
return strcmp($a, $b);
};
# the sort
$sort = function() use ($data, $compare)
{
$r = uasort($data, $compare);
if (!$r)
{
throw new RuntimeException('Sort failed.');
}
return $data;
};
print_r($sort());
Use usort to sort by a function. The function can contain any logic you want to put in, as long as the return value indicates sort order (see link for details).

Which PHP Array function should I use?

I have two arrays:
Array
(
[0] => Array
(
[id] => 1
[type] => field
[remote_name] => Title
[my_name] => title
[default_value] => http%3A%2F%2Ftest.com
)
[1] => Array
(
[id] => 2
[type] => field
[remote_name] => BookType
[my_name] => book-type
[default_value] =>
)
[2] => Array
(
[id] => 3
[type] => value
[remote_name] => dvd-disc
[my_name] => dvd
[default_value] =>
)
)
Array
(
[title] => Test
[book-type] => dvd
)
I need to take each key in the second array, match it with the my_name value in the first array and replace it with the corresponding remote_name value of the first array while preserving the value of the second array.
There's got to be some carrayzy function to help!
EDIT: There will also be a few cases that the value of the second array will need to be replaced by the value of the first array's remote_name where the value of the second array matches the value of the first array's my_name. How can I achieve this?
EG: book-type => dvd should turn into BookType => dvd-disc
Like so?:
$first = array(
array(
'id' => 1,
'type' => 'field',
'remote_name' => 'Title',
'my_name' => 'title',
'default_value' => 'http%3A%2F%2Ftest.com',
),
array(
'id' => 2,
'type' => 'field',
'remote_name' => 'BookType',
'my_name' => 'book-type',
'default_value' => '',
),
array(
'id' => 3,
'type' => 'value',
'remote_name' => 'dvd-disc',
'my_name' => 'dvd',
'default_value' => '',
),
);
$second = array(
'title' => 'Test',
'book-type' => 'dvd',
);
$map = array('fields' => array(), 'values' => array());
foreach ($first as $entry) {
switch ($entry['type']) {
case 'field':
$map['fields'][$entry['my_name']] = $entry['remote_name'];
break;
case 'value':
$map['values'][$entry['my_name']] = $entry['remote_name'];
break;
}
}
$new = array();
foreach ($second as $key => $val) {
$new[isset($map['fields'][$key]) ? $map['fields'][$key] : $key] = isset($map['values'][$val]) ? $map['values'][$val] : $val;
}
print_r($new);
Output:
Array
(
[Title] => Test
[BookType] => dvd-disc
)
Explanation:
The first loop collects the my_name/remote_name pairs for fields and values and makes them more accessible.
Like so:
Array
(
[fields] => Array
(
[title] => Title
[book-type] => BookType
)
[values] => Array
(
[dvd] => dvd-disc
)
)
The second loop will traverse $second and use the key/value pairs therein to populate $new. But while doing so will check for key/value duplicates in $map.
Keys or values not found in the map will be used as is.
foreach($arr1 as &$el) {
$el['remote_name'] = $arr2[$el['my_name']];
}
unset($el);
I am not aware of such a carrayzy function, but I know how you could do it:
//$array1 is first array, $array2 is second array
foreach($array1 as $key => $value){
if (isset($value['remote_name'], $value['my_name']) && $value['remote_name'] && $value['my_name']){
$my_name = $value['my_name'];
if (isset($array2[$my_name])) {
$remote_name = $value['remote_name'];
$array2[$remote_name] = $array2[$my_name];
//cleanup
unset($array2[$my_name]);
}
}
}

array transformation in php

how would you turn this array:
Array
(
[0] => 234234234
[1] => 657567567
[2] => 234234234
[3] => 5674332
)
into this:
Array
(
[contacts] => Array(
[0] => Array
(
[number] => 234234234
[contact_status] => 2
[user_id] =>3
)
[1] => Array
(
[number] => 657567567
[contact_status] => 2
[user_id] =>3
)
[3] => Array
(
[number] => 234234234
[contact_status] => 2
[user_id] =>3
)
[4] => Array
(
[number] => 5674332
[contact_status] => 2
[user_id] =>3
)
)
)
is there a cakephp specific way how to transform this array?
thank you
nicer
$contact_status = 2;
$user_id = 1;
foreach($input as $number)
$output['contacts'][] = compact('number', 'contact_status', 'user_id');
Try this:
$output = array('contacts'=>array());
foreach ($input as $val) {
$output['contacts'][] = array(
'number' => $val,
'contact_status' => 2,
'user_id' => 3
);
}
I assume that contact_status and user_id are static since you didn’t tell anything else.
$input = array(...);
$arr = array();
foreach ($input as $id) {
$arr[] = array(
'number' => $id,
'contact_status' => 2,
'userid' => 3;
);
}
$output = array('contacts' => $arr);
A little bit of cleanup from sterofrog's solution. Declare the array and use array_push instead of assigning it to an empty index.
$output = array( );
$contact_stats = 2;
$user_id = 3;
foreach( $input as $number ) {
array_push( $output[ 'contact' ], compact(
'number',
'contact_status',
'user_id'
));
}
You can simply use the array_map function like this:
$result = array_map(function ($n){
return array(
'number' => $n,
'contact_status' => 2,
'user_id' => 3);
}, $original);

Categories