I've tried many solutions here but they all seem to require a common key to sort the array by.
My var_dump() for the array is as follows:
array(10) { [0]=> string(11) "Agriculture" [2]=> string(6) "Metals" [12]=> string(10) "Sanitation" [14]=> string(19) "Health & Beauty" [22]=> string(13) "Oil & Gas" [27]=> string(12) "Construction" [31]=> string(13) "Manufacturing" [58]=> string(8) "Retailer" [61]=> string(11) "Distributor" [77]=> string(7) "Service" }
I'd like to be able to sort the strings in the array into the following order:
Service
Distributor
Retailer
Manufacturing
Construction
Oil & Gas
Health & Beauty
Sanitation
Metals
Agriculture
I know this is not an ideal solution but I really need to manually sort these.
Any help would be super appreciated. Thanks!
The main difference is that this one is generated from a database, so removing one from the databases should also remove it from the array. Hence why I can't manually create it.
So, I assume, that if one is added to the database, it should somehow also be "available"?
If one is renamed in the Database, sorting should still work?
The only reliable solution would be to add another column to the database table, let's call it position - and then fetch the entries and sort them by the position value, which could be 1 upto 10.
Hint on that: Start with a step size of thausand (1000,2000,3000,...) This allows you to add an item later somewhere in between without changing all subsequent item as well. (i.e. creating an entry with position 1500 would become the new second entry, and everything else will automatically shift one position down. If another "new second entry" shall be inserted, you can use 1250 and so on... Gives you some "time" until you have to finally reindex the positions - Use decimal/double if you want to keep this going forever^^)
For me it looks like you want to sort you array by index in descending order. For that you should use krsort() function.
http://php.net/manual/en/function.krsort.php
To sort an array in a reverse order use
array array_reverse ( array $array [, bool $preserve_keys = FALSE ]
Parameters
array
The input array.
preserve_keys
If set to TRUE numeric keys are preserved. Non-numeric keys are not affected by this setting and will always be preserved.
http://php.net/manual/en/function.array-reverse.php
Related
I'm using this to define the valid keys that can be used to perform a search on my front end:
$validKeys = array('gender','marital_status', 'age');
The rest of my code works great in that it only accepts keys sent to it in an AJAX call that are in this array.
However, I want to be able to make this list ('gender','marital_status', 'age') dynamic. That is, I'd like to include all of the columns from my table in here so that every column is essentially a valid key. I have about 10-15 depending on the table and I'd rather not hard-code it into each PHP file.
How would I go about getting all the column names in my table and arranging them into this variable? So, I need to get all the names, put them in single quotes and comma separate. Unless there's a way to get them in a proper array and skip the array part of defining the $validkeys variable.
If I var_dump $validKeys, I get this:
array(5) {
[0]=>
string(6) "gender"
[1]=>
string(14) "marital_status"
[2]=>
string(3) "age"
[3]=>
string(7) "anglers"
[4]=>
string(8) "baseball"
}
Any direction would be appreciated.
EDIT: Should have been more explicit that I am using PDO.
you can try with mysqli's fetch_fields-function.
$finfo = $result->fetch_fields();
Documentation: http://php.net/manual/de/mysqli-result.fetch-fields.php
Run a query using the DESCRIBE syntax. That will return all columns to you which you can then place in the array.
DESCRIBE `table_name`;
Another option is SHOW COLUMNS. Either will work for your requirements.
I should have been a bit more explicit that I am using PDO, so Jay's answer above pointed me in the right direction and I found this answer that gave me the details: https://stackoverflow.com/a/7091984/989722
The full code snippet based on my question looks like this:
$q = $dbh->prepare("DESCRIBE full_db2");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
$validKeys = $table_fields;
I have an array with a field of type string in php.
I'm using it to keep track of history. everytime a user performs a specified action the user id is added to the string. I'm using the RedBean ORM, so to declare the field varchar using mysql I have initialized it as:
$history_field="0 ,";
but when I perform:
$history_array= explode(',', $history_field);
I get:
array(2) { [0]=> string(2) "0 " [1]=> string(0) "" }
There should be one element in the array - namely '0' , I would have thought. Is this a bug?
how can I fix this to get my expected result. Thank you.
As per the documentation (and the comments) this is expected behavior, you can use this to filter out the empty values:
array_filter(explode(',', $history_field), 'strlen');
Basically, I have a bunch of files with a common prefix (logo%d.jpg) .
When they are viewed using ls or even when looping through a directory in PHP, I don't receive them in numerical order, meaning logo1.jpg, logo2.jpg.
Instead I get them in alphabetical order, like:
logo1.jpg, logo10.jpg, logo11.jpg ... logo 19.jpg, logo2.jpg (Instead of logo20.jpg)
Is there a way to ouput them in numerical order? logo1, logo2, logo3 .. etc.
You could put them in an array and sort the array with the natsortĀDocs function:
$array = array('logo1','logo2','logo12');
natsort($array);
Which gives (Demo):
array(3) {
[0]=>
string(5) "logo1"
[1]=>
string(5) "logo2"
[2]=>
string(6) "logo12"
}
The order you're looking for is often called natural order.
Alternatively, you could prefix the numbers, e.g. if you're already using sprintf to name the files, so that the standard sort order would still work:
`logo%03d.jpg`
Which would generate
logo001.jpg
for decimal 1.
Load into an array and use natsort()
If you're using ls like you say...
ls | sort -n
will do the trick.
I am trying to sort an array that contains numbers that range in substantial values. The result I want to get is a descending order of those numbers from the array I am retrieving from a MySQL Server. So far I have created this to test out the "sort" function:
<?php
$numbers = array("100", "50", "70", "1000");
sort($numbers);
echo var_dump($numbers);
?>
And the result I get is this:
array(4) { [0]=> string(2) "50" [1]=> string(2) "70" [2]=> string(3) "100" [3]=> string(4) "1000" }
I can see that the numbers are listing from smallest to largest, but I want it to list from the biggest integer to the smallest integer. Also I don't understand why it has text other than the integers. If anyone could help me out on this, I would greatly appreciate it.
Thanks,
Kevin
You need rsort to sort in reverse order:
rsort($numbers);
More Info:
http://php.net/manual/en/function.rsort.php
rsort() reverse sorts the array :)
you can use rsort to sort it descending.
http://www.developertutorials.com/tutorials/php/sorting-array-php-051114-1019/
Let me show you can find an answer yourself.
navigate to the manual page for the function you are currently using: http://php.net/sort
note especially easy address - just eight characters and a function name. Very handy.
scroll down to the See also section.
Pick appropriate function.
Done!
See, it's not that hard. And no need to accept any answers, cause you answered question yourself.
As for the text, there isn't any. Just try to use this array for something useful and see
I'm working on a little app that takes Excel spreadsheets that display tournament brackets, and then output the excel data and formatting into xml. I'm using Spreadsheet_Excel_Reader (https://code.google.com/archive/p/php-excel-reader/) to retrieve the data from the tournament bracket spreadsheets. The only problem is that any cell will no value will not be put in the Spreadsheet_Excel_Reader->sheets[0]['cells'] array, thus causing the table cell borders to not output. It appears that if I put a space in each cell that I want display, it works fine, but that seems like a pretty hackey way of doing it. Does anyone if there is a better way to output the formatting of a blank cell using the Spreadsheet_Excel_Reader?
I found this question after having the same problem (a spreadsheet row with 5 columns, 2 of them blank, are shown as an array of 3 items, omitting the 2 empty cells).
It took longer than I wanted it to, but I think I figured it out. When you dump your row data, check out the indexes.
array(5) {
["maxrow"]=>
int(0)
["maxcol"]=>
int(0)
["numRows"]=>
int(2)
["numCols"]=>
int(3)
["cells"]=>
array(2) {
[1]=>
array(2) {
[1]=>
string(4) "test"
[2]=>
string(3) "xls"
}
[2]=>
array(2) {
[1]=>
string(5) "empty"
[3]=>
string(4) "test"
}
}
}
In my case, I have an empty cell in the second row, between "empty" and "test", and I can see that "test" as the index '3'.
What you (and I) need to do is, instead of using foreach(), be sure to iterate over each expected index using for() or foreach(range()) ending at numCols.