Reputation: 660
I'm building an app using laravel/php. I having using how to map and sort my array. Is there anyone can help me how to fix this? I have this two different array. The first picture is the label and second is my data.
I am trying to map the label to data and sort my data to min to max But I only did it using javascript.
Here is my sample code.
$arrayOfObjIssues = $arrayLabelIssues.map(function($d, $i) {
return {
label: $d,
data: $arrayDataIssues[$i] || 0
};
});
$sortedArrayOfObjIssues = $arrayOfObjIssues.sort(function($a, $b) {
return $b.data>$a.data;
});
$newArrayLabelIssues = [];
$newArrayDataIssues = [];
$sortedArrayOfObjIssues.forEach(function($d){
$newArrayLabelIssues.push($d.label);
$newArrayDataIssues.push($d.data);
});
How can I able to fix this? All help are welcome. Thank you in advance.
Upvotes: 1
Views: 10564
Reputation: 202
in collection if it has same value then it will not map each value u can also try this
$keys = ['B', 'C', 'A'];
$values = [1, 2, 3];
for($i = 0; $i < sizeof($keys); $i++){
$maping[$keys[$i]] = $values [$i];
} // output ['B' => 1, 'C' => 2, 'A' => 3]
Upvotes: 0
Reputation: 6544
With the use of Laravels collections, this is fairly simple:
$keys = ['B', 'C', 'A'];
$values = [1, 2, 3];
$collection = \Illuminate\Support\Collection::make($keys); // state: ['B', 'C', 'A']
$combined = $collection->combine($values); // state: ['B' => 1, 'C' => 2, 'A' => 3]
$sorted = $combined->sortKeys(); // state: ['A' => 3, 'B' => 1, 'C' => 2]
$sorted->toArray(); // to get the result back as array like shown above
For further reference, have a look at the available collection methods.
Upvotes: 2
Reputation: 2227
In PHP we use ->
rather than .
dot notation.
And if $arrayLabelIssues
is a plain PHP array you have to first convert it to Laravel collection to be able to use its functions.
So you would do something like this:
$arrayLabelIssues = collect($arrayLabelIssues); // now it's a Laravel Collection object
// and you can use functions like map, foreach, sort, ...
$arrayLabelIssues->map(function($item) {
// ... your code
});
Upvotes: 2
Reputation: 7571
Try this (you dont need Laravel's Collection in particular):
// Create empty array that will contain $arr1 as keys and $arr2 as values
$newArray = [];
foreach($arr1 as $i => $item) {
// Match the two arrays together. Get the same index from the 2nd array.
$newArray[$item] = $arr2[$i];
}
// Sort the list by value
asort($newArray);
Upvotes: 2