i have added a new array to my elements like this code :
$elements= Code::get();
foreach($elements as $element){
$string = str_random(15);
$element->total = $string;
}
I would like to return elements after set orderBy() on total using this code
return response()->json(['Status'=> '1','Elements' => $elements ]);
Thank you and i appreciate you help.
Well this is not how foreach
works actually. foreach
creates a "mirror" of your array so doing any insertion on $element
does not affect your initial array at all.
You need to insert your value directly in your array, so you can either use a counter or simpler a for loop.
I will modify your foreach to stay similar to your approach.
Judging by how you tried to insert the value in your array i assume you have a collection and not an array so if that's the case you can add this line before everything:
$elements = $elements->toArray(); //convert collection to array
$counter = 0;
foreach($elements as $element){
$string = str_random(15);
$elements[$counter]['total'] = $string;
$counter++;
}
Your $elements
array now has the field total in each of the nested arrays.
Then you simple do:
array_multisort( array_column($elements, "total"), SORT_ASC, $elements);
If you want to sort in descending order simple use SORT_DESC
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments