Lets say I have this array:
$array = array('a'=>1,'z'=>2,'d'=>4);
Later in the script, I want to add the value 'c'=>3
before 'z'
. How can I do this?
EDIT: Yes, the order is important. When I run a foreach() through the array, I do NOT want this newly added value added to the end of the array. I am getting this array from a mysql_fetch_assoc()
EDIT 2: The keys I used above are placeholders. Using ksort() will not achieve what I want.
EDIT 3: http://www.php.net/manual/en/function.array-splice.php#88896 accomplishes what I'm looking for but I'm looking for something simpler.
EDIT 4: Thanks for the downvotes. I gave feedback to your answers and you couldn't help, so you downvoted and requested to close the question because you didn't know the answer. Thanks.
EDIT 5: Take a sample db table with about 30 columns. I get this data using mysql_fetch_assoc(). In this new array, after column 'pizza' and 'drink', I want to add a new column 'full_dinner' that combines the values of 'pizza' and 'drink' so that when I run a foreach() on the said array, 'full_dinner' comes directly after 'drink'
An alternative approach is to supplement the associative array structure with an ordered index that determines the iterative order of keys. For instance:
A simple approach to this is to iterate through the original array, constructing a new one as you go:
Then simply call
For the moment the best i can found to try to minimize the creation of new arrays are these two functions :
the first one try to replace value into the original array and the second one return a new array.
You can define your own sortmap when doing a bubble-sort by key. It's probably not terribly efficient but it works.
Here's an approach based on ArrayObject using this same concept
Great usage of array functions but how about this as a simpler way:
Add a static column to the SQL and then replace it in the resultant array. Order stays the same:
SQL :
Array :
Am I missing something?
Handling of nonexistent keys (appending
$data
by default):Demo: