Hello All i want to sort the array in the way that
ASC order of user id
there is array like $user
i want to sort on the base
id $user['role'] =1;
then that element will set at the top of the array
Look in the PHP manual at asort, sort, and ksort. I'm not exactly sure what you're asking, but one of them is bound to do what you need.
Does that information come from a database? In that case, doing something like ORDER BY role DESC, user_id would be better than having PHP sort it for you.
If your array example $user['role'] = 1 means that 1 is the user id you want to use sort($user); however if role is going to be numeric you would want asort($user); instead as sort will overwrite numeric keys. As #Rob above said you may want to use ksort but only if you are making the array $user[user_id] = role.
Hope this helps
Regards
Luke
Thanx All For Replying on my question
i got the solution here it is
function compare($a,$b)
{
return strcmp($a["role"]['ID'], $b["role"]['ID']);
}
usort($a,compare);
Related
Instead of working with mysql data, I have created csv file that I plan to use as the source of data for content, etc.
And I have successfully been able to parse the csv and store it into a complex array, that has the following header row aka the keys for the arrays.
"Title","Year","Rated","Released","Runtime","Genre","Director","Writer","Actors","Plot","Language","Country","Awards","Poster","Metascore","imdbRating","imdbVotes","imdbID","Type","Response"
My current stage is to allow dynamic ajax sorting of the arrays.
I have two fields, that I am allowing sorting at the beginning, "Year" and "Title".
So I pass different url paramters, such as "yearasc" or "yeardesc" or "titleasc" or "titledesc".
Then try to sort for that.
So what I did reading a different so post, was to do this.
First I create new arrays that only store the key fields, I need for sorting.
Then based on what sort type, do a different array_multisort.
array_multisort($year, SORT_ASC, $all_rows);
But what I get is results that multiple dupplicate data.
But I wonder if having the first row, be the header row, which is required by the function I pass the data after any sorting to, is causing issues with array sorting.
For simple array sorting, existing functions makes sense and work fine.
But for complicated ones, it is just complex to even understand how to approach solving this problem.
Any suggestions, thoughts or ideas are appreciated and thanked.
Thank you!
I don't have the actual code that is probably going to help you, but I do have a suggestion as for how you can tackle this and make it work..
Keep it simple. First, create your own CSV with just 1 header (Year or Title ) that you want to sort on.
Write your code to sort on that.
Then, add the other one ( Title if you used Year before, or Year if you used Title before ) and sort on whichever you want.
Then, add one more header (say, Rated) that you don't want to sort on.
You should then be able to work with the original CSV.
I'd try to write simple methods and keep your processing to a minimum in each one.
I hope that helps. I realize its more philosophical of an answer, so it is hit or miss if it helps you get the job done. Just realize that this approach will, indeed, take a little more time to write - but the point behind it is that you're taking out all of the "noise" that's getting in your way first. It helps you look at only your problem first and solve that.
You can set a custom sort function to the array. Use asort() if you need to keep original array keys.
<?php
$sortfields = array('year', 'bleh');
function cmp($a, $b) {
global $sortfields;
foreach ($sortfields as $sortfield) {
$cmp = strcmp($a[$sortfield], $b[$sortfield]);
// if desc, invert sign of $cmp
if ($cmp !== 0)
return $cmp;
}
return 0;
}
usort($all_rows, "cmp");
The function usort() calls a user defined comparison function, which returns the same logic from strcmp function: 0 if equal, < 0 is $a is less than $b and > 0 if $a is greater than $b.
This function will compare each field set in $sortfields variable, if it find any comparison that is different (in the order set), it will immediately return the difference.
I have an array of unique colors which is selected from a table. But keys of that particular array is not in sequence order due to some calculations. Now I wish to assign a sequence numbers to that array... Is any function to change keys of array..
Thanks...
Array(
[81]=>yellow
[86]=>gray
[93]=>wine
[103]=>marigold
[125]=>maroon
[134]=>pewter
[142]=>forestgreen
[151]=>grey
)
i wish to change this array to
Array(
[1]=>yellow
[2]=>gray
[3]=>wine
[4]=>marigold
[5]=>maroon
[6]=>pewter
[7]=>forestgreen
[8]=>grey)
If you want to sort your array by some calculation, you can use usort(), which sorts an array by using a callback function. In this callback function, you can compare two elements of the array and decide (by any means you need) which one goes first. Read through the examples on the page I linked to learn more!
use: sort($color); check the examples from this link: sort
I woud like to sort an array which typically includes names and email addresses. The problem is that the email addresses appear last even though they may start with 'a'
e.g.
$myarray = ("Alex Mayfeild", "David Beckham", "Oliver Twist", "ant.stev#wherever.com", "peter.pan#neverland.com", ........) //and so on
Upon sorting the array using php's sort function "ant.stev#wherever.com" will appear close to the end even though the functionality I would like to achieve is for him to appear after Alex.
natcasesort and natsource functions based on natural ordering seem to fail. Correction: natcasesource works it returns true when working as stated in docs. Thanks #meagar
Is there anyway to achieve the requested functionality. Thanks for any help guys. It is very much appreciated.
sort() is case sensitive, as it sorts based on the letters ASCII value.
Try natcasesort(), if you want too "sort an array using a case insensitive 'natural order' algorithm".
Seems to me that sort($myarray, SORT_STRING|SORT_FLAG_CASE); should sort the array the way you want.
I have an array:
$data = array(
'loggedin' => false
);
i want to add other keys as well their values if the user is logged in so i use:
if ( $this->auth_model->loggedin()){//user is logged in
$data["loggedin"] = true;//set to true
$data["user_id"] = $this->session->userdata["uid"];//add new key with its value on $data array
}
is this the best way to do it or should i use array_push and such?
No need to add overhead by calling a function (like array_push).
Yes. That's the way to do it.
With array_push you cannot set the key.
The way you have described is the fastest one.
You can create a second array with user_id key and then merge those two arrays, but this is not a good way to solve this case.
Stay with that you have right now.
i don't think you can use array_push to add values to an associative array, so it's ok to do as you are doing
The way you are adding is better than using array_push (reason: you are inserting few values and it avoid the overhead of calling a function) if you are adding more values to this array, then you can use array_push.
I need to create an association between an Array and a Number; as PHP lacks a Map type, I am trying using an array to achieve this:
$rowNumberbyRow = array();
$rowNumberByRow[$rowData] = $rowNumber;
However, when I evaluate the code, I get the following Error:
Warning: Illegal offset type
Just to note, the data stored in the array ($rowData) does not have any 'unique' values that I can use as a key for the $rowNumberByRow Array.
Thanks!
UPDATE:
To answer some of my commenters, I am trying to create a lookup table so that my application can find the row number for a given row in O(1) time.
PHP does have a map Class: It's called SplObjectStorage. It can be accessed with exactly the same syntax as a general array is (see Example #2 on the reference).
But to use the class you will have to use the ArrayObject class instead of arrays. It is handled exactly the same way arrays are and you can construct instances from arrays (e.g. $arrayObject = new ArrayObject($array)).
If you don't want to use those classes, you can also just create a function that creates unique hash-strings for your indexes. For example:
function myHash($array){
return implode('|',$array);
}
$rowNumberByRow[myHash($array)] = $rowNumber;
You will of course have to make sure that your hashes are indeed unique, and I would strongly suggest you use the SplObjectStorage and maybe read a little bit more about the SPL classes of php.
Why not just store the row number in the array? e.g:
$rowData['rowNumber'] = $rowNumber;
You could instead serialize the array, e.g:
$rowNumberByRow[serialize($rowData)] = $rowNumber;
However that's pretty inefficient.
In php you can use only scalar values as an array keys.
If your $rowNumber is unique - then you'd try to use the opposite relation direction. If it is not unique - then you don't have any possible solution I know.
The answer has been alredy given and accepted, but while i was searching for a similar problem, i found this question, and i felt like i should drop a line: when someone wants to use an array with values as keys for another array, it would be useful to use the function array_combine.
If i got the arrays correctly, you could use:
$rowNumberByRow = array_combine($rowData, $rowNumber);
Please take a look at the PHP manual to see some info about permitted values for the keys :)