Reputation: 23
I have an array that I would like to sort, that should be easy, except that I build my array in a strange manners (for different reasons) that make it hard to sort. Here is my array :
$arrayCEO =array(
'companyName' => array(0=>'name1', 1=>'name2'),
'link' => array (0=>'link1', 1=>'link2'),
'isin' => array (0=>'isin1', 1=>'isin2'),
'mktCap' => array (0=>'mktCap1', 1=>'mktCap2'),
'nbShares' => array (0=>'nbShares1', 1=>'nbShares2'),
'amount' => array (0=>'10', 1=>'20'));
Is that possible to sort by "amount" without breaking the order in the others arrays? Do you recommend me to rewrite my code to build an array like this one :
$arrayCEO =array(
0 => array ('name' => 'name1', 'link' => 'link1', 'isin' => 'isin1', …),
1 => array ('name' => 'name2', 'link' => 'link2', 'isin' => 'isin2', …));
2 => ...
I know this one would be simple to sort but it's a lot of work to rewrite my piece of code.
Upvotes: 2
Views: 78
Reputation: 47894
Is that possible to sort by "amount" without breaking the order in the others arrays?
Yes, array_multisort()
is a native function designed to maintain positional relationships while sorting multiple arrays sharing the same element count. ASC Demo, DESC Demo
$arrayCEO = [
'companyName' => ['name1', 'name2', 'name3'],
'link' => ['link1', 'link2', 'link3'],
'isin' => ['isin1', 'isin2', 'isin3'],
'mktCap' => ['mktCap1', 'mktCap2', 'mktCap3'],
'nbShares' => ['nbShares1', 'nbShares2', 'nbShares3'],
'amount' => ['10', '20', '15']
];
array_multisort(
$arrayCEO['amount'],
// SORT_DESC
$arrayCEO['companyName'],
$arrayCEO['link'],
$arrayCEO['isin'],
$arrayCEO['mktCap'],
$arrayCEO['nbShares']
);
var_export($arrayCEO);
Do you recommend me to rewrite my code to [transpose the array structure to facilitate sorting]?
Designing data structures is too nuanced for an outside party to determine without a more intimate understanding of all the ways that the data will be processed/managed. It may be worthwhile to refactor the data structure or it might not. Is this data hardcoded, constant/variable, saved in a file, saved in a database? Depending on how often the data is written or read, the data storage itself may need to be reconsidered. Performance and memory matter, but so does code readability and maintainability -- programming is often about acceptable tradeoffs.
Upvotes: 0
Reputation: 974
It makes a lot more sense to rewrite your arrays to store in the more conventional format you described - (It's always better to organise things in decreasing magnitude 'Root > rows > fields' instead of 'Root > fields > rows')
If you didn't want to change you could probably use the usort function and roll your own sorting method, but it might be a bit of work to make it play nicely.
Upvotes: 1