Merging overlapping ranges in PHP arrays? - php

I have an array in the following format:
array(
0 => array(1, 5),
1 => array(4, 8),
2 => array(19, 24),
3 => array(6, 9),
4 => array(11, 17),
);
Where each item is a X-to-Y range. What I would like to merge the overlapping ranges in the array, to get something more like this:
array(
0 => array(1, 9), // 1-5, 4-8 and 6-9 are overlapping, so they are merged
1 => array(11, 17),
2 => array(19, 24),
);
What would be the best way to accomplish this?

Untested, but the idea here is to sort the data first by the first element, then merge subsequent elements with the previous one as long as possible.
usort($data, function($a, $b)
{
return $a[0] - $b[0];
});
$n = 0; $len = count($data);
for ($i = 1; $i < $len; ++$i)
{
if ($data[$i][0] > $data[$n][1] + 1)
$n = $i;
else
{
if ($data[$n][1] < $data[$i][1])
$data[$n][1] = $data[$i][1];
unset($data[$i]);
}
}
$data = array_values($data);

$input = array( 0 => array(1, 5),
1 => array(4, 8),
2 => array(19, 24),
3 => array(6, 9),
4 => array(11, 17),
);
$tmpArray = array();
foreach($input as $rangeSet) {
$tmpArray = array_unique(array_merge($tmpArray,range($rangeSet[0],$rangeSet[1])));
}
sort($tmpArray);
$oldElement = array_shift($tmpArray);
$newArray = array(array($oldElement));
$ni = 0;
foreach($tmpArray as $newElement) {
if ($newElement > $oldElement+1) {
$newArray[$ni++][] = $oldElement;
$newArray[$ni][] = $newElement;
}
$oldElement = $newElement;
}
$newArray[$ni++][] = $oldElement;
var_dump($newArray);

Alright, drafted this up, so it may have quirks. Tested it with the data seen below and seemed to work just fine. May not be the best way to do it, but it is one way and it does work. Questions let me know.
function combineRange($array) {
if (is_array($array)) {
// Sort the array for numerical order
sort($array);
// Set Defaults
$prev = array();
$prev_key = null;
foreach ($array as $key => $item) {
// First time around setup default data
if (empty($prev)) {
$prev = $item;
$prev_key = $key;
continue;
}
if ($item[0] >= $prev[0] && $item[0] <= $prev[1]) {
// Incase the last number was less than do not update
if ($array[$prev_key][1] < $item[1])
$array[$prev_key][1] = $item[1];
unset($array[$key]);
}else {
$prev_key = $key;
}
$prev = $item;
}
}
return $array;
}
$array = array(
5 => array(13, 16),
0 => array(1, 5),
1 => array(4, 8),
2 => array(19, 24),
3 => array(6, 9),
4 => array(11, 17),
6 => array(21, 30),
);
var_dump(combineRange($array));
Outputs:
array(3) {
[0]=>
array(2) {
[0]=>
int(1)
[1]=>
int(9)
}
[3]=>
array(2) {
[0]=>
int(11)
[1]=>
int(17)
}
[5]=>
array(2) {
[0]=>
int(19)
[1]=>
int(30)
}
}
Hope it works for ya!
EDIT
I see I was beaten out by an hour =\ Oh well! I am still posting as it is a different method, granted I would probably choose konforce's method instead.

Related

Loop through array of values and sort

I would like you to help me with an algorithm in PHP that can loop through an array of values, sort them and print non-duplicates.
Here is the code I wrote. I want to do it with only loop and if else statement. I would appreciate any help in achieving this. Thanks
$input_array = [3, 5, 7, 7, 8, 3, 1, 9, 9, 9, 0, 2, 4, 8, 0, 12, 5, 8, 2];`
$count_array = count($input_array); // count the array`enter code here`
for($i = 0; $i < $count_array; $i++){ //loop through the array 1st time
$check_array = false;
//sort array
for($j = $i+1; $j < $count_array; $j++){
if($input_array[$i] > $input_array[$j]){
$non_duplicates = $input_array[$i];
$input_array[$i] = $input_array[$j];
$input_array[$j] = $non_duplicates;
}
else if($input_array[$i] == $input_array[$j] &&( $i != $j)){
$check_array = true;
break;
}
else{
$input_array[$i] != $input_array[$j];
}
}
if(!$check_array){
echo($input_array[$i]. ', ');
}
}
You can do it with 2 for cycles where the first cycle is for the first element and the 2nd cycle is always in the next position, this will help to always check if the first number is less than the second. You create a temporary variable where you store the value of the first number and you pass the value of the second number to the variable of the first one, later the temporary one that you had stored you pass it to the variable of the second number (with this you got to invert the values of one to the other).
As this is ordering them, later an if is made where it is verified if they are equal, in case of being equal a unset() is made to eliminate that data of the array.
// Array of values
$input_array = [3, 5, 7, 7, 8, 3, 1, 9, 9, 9, 0, 2, 4, 8, 0, 12, 5, 8, 2];
// count the length of array
$count = count($input_array);
// order array and remove duplicates
for ($i = 0; $i < $count; $i++) {
for ($j = $i + 1; $j < $count; $j++) {
// order array
if ($input_array[$i] < $input_array[$j]) {
$temp = $input_array[$i];
$input_array[$i] = $input_array[$j];
$input_array[$j] = $temp;
}
// delete duplicates
if ($input_array[$i] == $input_array[$j]) {
unset($input_array[$j]);
}
}
}
// Return an array with elements in reverse order
$input_array = array_reverse($input_array);
You get something like this:
Dump => array(9) {
[0] => int(1)
[1] => int(2)
[2] => int(3)
[3] => int(4)
[4] => int(7)
[5] => int(5)
[6] => int(8)
[7] => int(9)
[8] => int(12)
}

Sum current month value with previous last 5 month value in array

I have an array with some values. Here I need to make a calculation for Year 2019 only.
$array = array(
"date_2019_12" => 0,
"date_2019_11" => 0,
"date_2019_10" => 0,
"date_2019_09" => 0,
"date_2019_08" => 0,
"date_2019_07" => 0,
"date_2019_06" => 0,
"date_2019_05" => 0,
"date_2019_04" => 0,
"date_2019_03" => 0,
"date_2019_02" => 0,
"date_2019_01" => 10,
"date_2018_12" => 1,
"date_2018_11" => 2,
"date_2018_10" => 3,
"date_2018_09" => 4,
"date_2018_08" => 5,
"date_2018_07" => 6,
);
krsort($array);
From this array, I need to calculate the sum of previous five months & current month starting "date_2019_01".
That means I need final array result like below:
"date_2019_01" => 25(10+1+2+3+4+5)
"date_2019_02" => 20(0+10+1+2+3+4)
"date_2019_03" => 16(0+0+10+1+2+3)
"date_2019_04" => 13(0+0+0+10+1+2)
... until "date_2019-12".
I have spend many times finding solution but I could not. Can anybody help me?
I have tried following code and somewhere now I am lost.
$newArr = array();
foreach($array as $key => $val) {
$explode = explode("_", $key);
$value = (int)$explode[2];
for($i = 0; $i <= 5; $i++) {
$newArr[$array[$explode[0].'_'.$explode[1].'_'.$value]] = $array[$explode[0].'_'.$explode[1].'_'.$value];
$value--;
}
}
You don't need to nest the loops, you can use one loop, array_slice and array_sum.
krsort($array);
$year = "2019";
$keys = array_keys($array); //save keys since we use array_values in the loop
foreach(array_values($array) as $k => $v){
// If the year is found in the key slice out the next six item and sum them
if(strpos($keys[$k], $year) !== false) $res[$keys[$k]] = array_sum(array_slice($array, $k, 6));
}
var_dump($res);
https://3v4l.org/LSQRg
This code will do what you want. It uses a nested loop to iterate over each month and the 5 preceding months, creating a sum for each one from the different date values in the array:
$year = 2019;
$sums = array();
for ($i = 1; $i <= 12; $i++) {
$sum = 0;
for ($j = $i - 5; $j <= $i; $j++) {
$y = $year;
$m = $j;
if ($m <= 0) {
$m += 12;
$y -= 1;
}
$date = sprintf("date_%4d_%02d", $y, $m);
$sum += $array[$date];
}
$date = sprintf("date_%4d_%02d", $year, $i);
$sums[$date] = $sum;
}
print_r($sums);
Output:
Array (
[date_2019_01] => 25
[date_2019_02] => 20
[date_2019_03] => 16
[date_2019_04] => 13
[date_2019_05] => 11
[date_2019_06] => 10
[date_2019_07] => 0
[date_2019_08] => 0
[date_2019_09] => 0
[date_2019_10] => 0
[date_2019_11] => 0
[date_2019_12] => 0
)
Demo on 3v4l.org
Use: https://3v4l.org/7AYfT
$newArr = array();
foreach($array as $key => $val) {
$i=1;
$newArr[$key] = $val;
foreach($array as $key2 => $val2){
if($key>$key2 && $i <= 5){
$newArr[$key] += $val2;
$i++;
}
}
}
array(18) {
["date_2019_12"]=>
int(0)
["date_2019_11"]=>
int(0)
["date_2019_10"]=>
int(0)
["date_2019_09"]=>
int(0)
["date_2019_08"]=>
int(0)
["date_2019_07"]=>
int(0)
["date_2019_06"]=>
int(10)
["date_2019_05"]=>
int(11)
["date_2019_04"]=>
int(13)
["date_2019_03"]=>
int(16)
["date_2019_02"]=>
int(20)
["date_2019_01"]=>
int(25)
["date_2018_12"]=>
int(21)
["date_2018_11"]=>
int(20)
["date_2018_10"]=>
int(18)
["date_2018_09"]=>
int(15)
["date_2018_08"]=>
int(11)
["date_2018_07"]=>
int(6)
}
There are two steps I have performed.
Step 1: Sorting custom format array by keys
// sort the array first by date of given format
uksort($array, function ($a, $b) {
$t1 = strtotime(str_replace(["date_", "_"], ["", "-"], $a) . '-01');
$t2 = strtotime(str_replace(["date_", "_"], ["", "-"], $b) . '-01');
return $t1 - $t2;
});
Step 2: Main logic to given condition with inline documentation
$flag = false;
$result = [];
foreach ($array as $key => $value) {
if ($key != 'date_2019_01' && !$flag) {
continue; // check until 'date_2019_01' wont come
} else {
$flag = true; // set the flag and skip above condition
$curKey = array_search($key, array_keys($array), true); // get integer index of date_2019_01
if ($key !== false) { // if key exists
$slice = array_slice($array, $curKey - 5, 6, true); // from current index last 5(6-5, 7-5,8-5,....) to 6(including current element)
$result[$key] = array_sum($slice); // sum of there values
}
}
}
Brief of things I have used to make it clear for understanding of applications of it.
uksort — Sort an array by keys using a user-defined comparison function
array_keys — Return all the keys or a subset of the keys of an array
array_search — Searches the array for a given value and returns the first corresponding key if successful
array_slice — Extract a slice of the array
array_sum — Calculate the sum of values in an array
str_replace — Replace all occurrences of the search string with the replacement string

PHP - get array value if next element is not series

Here is my array
$array = array( 0 => 10, 1 => 9, 2 => 8, 3 => 6, 4=> 4 );
I want to get array value 6. because, 7 is missing before this value/series is break.
Please help me how can I do it easy & fast method.
The sequence could be calculated by subtracting the first value from the second value. Then you could for example use a for loop to loop through the values of the array and check if there is also a next value available by checking if there is an index + 1.
Then if that is the case you can subtract the current value in the loop from the next value and check if that result equals the step size.
If that is not the case, the next value of the iteration is the value that breaks the sequence and you can break out of the loop.
$array = [10,9,8,6,4];
if (count($array) > 2) {
$step = $array[0] - $array[1];
for ($i = 0; $i < count($array); $i++) {
if (isset($array[$i + 1]) && $array[$i] - $array[$i + 1] !== $step) {
$wrongValue = $array[$i + 1];
echo sprintf(" The step count is %d, but after %d comes %d which breaks the sequence.",
$step, $array[$i], $wrongValue
);
break;
}
}
}
Demo
<?php
$sequence =
[
0 => 10,
1 => 9,
3 => 8,
4 => 6,
5 => 4
];
$last = null;
foreach($sequence as $k => $v)
{
if(!is_null($last) && $last - $v > 1)
break;
$last = $v;
}
var_dump($k, $v);
Output:
int(4)
int(6)
Loop through it, save the previous values and compare with current one:
<?php
function findMissing($array) {
$missing = [];
foreach($array as $key => $val) {
if(isset($previousValue) && $previousValue-1!=$val) {
echo "not in series: ".($previousValue-1) .", returning ".$val."<br>\n";
$missing[] = $val;
}
$previousValue=$val;
}
return $missing;
}
// USAGE:
$array = array( 0 => 10, 1 => 9, 2 => 8, 3 => 6, 4=> 4 );
findMissing($array);
// not in series: 7, returning 6
// not in series: 5, returning 4
$array2 = array( 10, 9, 8, 6, 5 );
$missingValues = findMissing($array2);
// not in series: 7, returning 6
var_dump($missingValues);
// array(1) { [0]=> int(6) }
I'm not sure I understand what you want to achieve, but let's start it here.
UPDATED:
for($i = 0; $i < count($array); ++$i) {
if($i > 0) {
if($array[$i] != ($array[$i-1]-1)) {
echo($array[$i]);
break;
}
}
}
Output:
6

Sorting multidimensional number array in PHP

I have issues sorting an multidimensional array.
The array looks like:
$array = array(
array("token" => array(100, 240, 348, 23, 17),
array("token" => array(293, 28, 283, 2, 28),
array("token" => array(842, 23, 72, 98, 114)
);
Now I want to sort them by "column". That means, the first column of numbers (100, 293, 842) must be sorted, then the second column (but keeping the first column as it is! It may happen that the columns have the same number with multiple rows) and so on.
Actually I tried this to do with usort(), but this will work only when sorting the first column:
function do_sort($a, $b) {
$tok_a = $a["token"];
$tok_b = $b["token"];
if ($tok_a[0] <= $tok_b[0])
return false;
else
return true;
}
usort($array, "do_sort");
How can I do this? Thanks
Here's possible solution:
get rid of 'token', i.e., make 2D array
swap columns and rows (transpose array)
sort each column
swap back columns and rows (get initial structure)
put 'token' back
Code:
function array_transpose(array $array) {
$result = array();
foreach ( $array as $rowNum => $row ) {
foreach ( $row as $colNum => $value ) {
$result[$colNum][$rowNum] = $value;
}
}
return $result;
}
$array = array(
array("token" => array(100, 240, 348, 23, 17)),
array("token" => array(293, 28, 283, 2, 28)),
array("token" => array(842, 23, 72, 98, 114)),
);
// get rid of 'token'
foreach ( $array as &$item ) {
$item = $item['token'];
}
unset($item);
// swap columns and rows
$array = array_transpose($array);
// sort columns
foreach ( $array as &$item ) {
sort($item);
}
unset($item);
// swap back columns and rows
$array = array_transpose($array);
// put 'token' back
foreach ( $array as &$item ) {
$item = array('token' => $item);
}
unset($item);
// display results
foreach ( $array as $row ) {
foreach ( $row['token'] as $value ) {
printf('%-7d', $value);
}
echo "\n";
}
Output:
100 23 72 2 17
293 28 283 23 28
842 240 348 98 114
I think this will do what you are after. I've made some assumptions here (such as $array is really an array, has at least one sub-array, all sub-arrays have token as the key, and all sub-arrays have the same number of elements).
<?php
$array = array(
array("token" => array(100, 240, 348, 23, 17)),
array("token" => array(293, 28, 283, 2, 28)),
array("token" => array(842, 23, 72, 98, 114)),
);
$count_outer = count($array);
$count_inner = count($array[0]['token']);
for ($i=0; $i < $count_inner; $i++) {
$temp_arr = array();
for ($j=0; $j < $count_outer; $j++) {
$temp_arr[] = $array[$j]['token'][$i];
}
sort($temp_arr);
for ($j=0; $j < $count_outer; $j++) {
$array[$j]['token'][$i] = $temp_arr[$j];
}
}
foreach ($array as $value) {
var_dump($value);
echo '<br>';
}
Output:
array(1) { ["token"]=> array(5) {
[0]=> int(100) [1]=> int(23) [2]=>
int(72) [3]=> int(2) [4]=> int(17) } }
array(1) { ["token"]=> array(5) {
[0]=> int(293) [1]=> int(28) [2]=>
int(283) [3]=> int(23) [4]=> int(28) }
} array(1) { ["token"]=> array(5) {
[0]=> int(842) [1]=> int(240) [2]=>
int(348) [3]=> int(98) [4]=> int(114)
} }
Can't you just
foreach ($array as &$item) {
sort($item['token']);
}
Or have I misunderstood the question?

How to add an array value to the middle of an associative array?

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?
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()
The keys I used above are placeholders. Using ksort() will not achieve what I want.
http://www.php.net/manual/en/function.array-splice.php#88896 accomplishes what I'm looking for but I'm looking for something simpler.
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'
Am I missing something?
$key = 'z';
$offset = array_search($key, array_keys($array));
$result = array_merge
(
array_slice($array, 0, $offset),
array('c' => 3),
array_slice($array, $offset, null)
);
Handling of nonexistent keys (appending $data by default):
function insertBeforeKey($array, $key, $data = null)
{
if (($offset = array_search($key, array_keys($array))) === false) // if the key doesn't exist
{
$offset = 0; // should we prepend $array with $data?
$offset = count($array); // or should we append $array with $data? lets pick this one...
}
return array_merge(array_slice($array, 0, $offset), (array) $data, array_slice($array, $offset));
}
Demo:
$array = array('a' => 1, 'z' => 2, 'd' => 4);
// array(4) { ["a"]=> int(1) ["c"]=> int(3) ["z"]=> int(2) ["d"]=> int(4) }
var_dump(insertBeforeKey($array, 'z', array('c' => 3)));
// array(4) { ["a"]=> int(1) ["z"]=> int(2) ["d"]=> int(4) ["c"]=> int(3) }
var_dump(insertBeforeKey($array, 'y', array('c' => 3)));
A simple approach to this is to iterate through the original array, constructing a new one as you go:
function InsertBeforeKey( $originalArray, $originalKey, $insertKey, $insertValue ) {
$newArray = array();
$inserted = false;
foreach( $originalArray as $key => $value ) {
if( !$inserted && $key === $originalKey ) {
$newArray[ $insertKey ] = $insertValue;
$inserted = true;
}
$newArray[ $key ] = $value;
}
return $newArray;
}
Then simply call
$array = InsertBeforeKey( $array, 'd', 'c', 3 );
According to your original question the best answer I can find is this:
$a = array('a'=>1,'z'=>2,'d'=>4);
$splitIndex = array_search('z', array_keys($a));
$b = array_merge(
array_slice($a, 0, $splitIndex),
array('c' => 3),
array_slice($a, $splitIndex)
);
var_dump($b);
array(4) {
["a"]=>
int(1)
["c"]=>
int(3)
["z"]=>
int(2)
["d"]=>
int(4)
}
Depending on how big your arrays are you will duplicate quite some data in internal memory, regardless if you use this solution or another.
Furthermore your fifth edit seems to indicate that alternatively your SQL query could be improved. What you seem to want to do there would be something like this:
SELECT a, b, CONCAT(a, ' ', b) AS ab FROM ... WHERE ...
If changing your SELECT statement could make the PHP solution redundant, you should definitely go with the modified SQL.
function insertValue($oldArray, $newKey, $newValue, $followingKey) {
$newArray = array ();
foreach (array_keys($oldArray) as $k) {
if ($k == $followingKey)
$newArray[$newKey] = $newValue;
$newArray[$k] = $oldArray [$k];
}
return $newArray;
}
You call it as
insertValue($array, 'c', '3', 'z')
As for Edit 5:
edit your sql, so that it reads
SELECT ..., pizza, drink, pizza+drink as full_meal, ... FROM ....
and you have the column automatically:
Array (
...
'pizza' => 12,
'drink' => 5,
'full_meal' => 17,
...
)
Associative arrays are not ordered, so you can simply add with $array['c'] = 3.
If order is important, one option is switch to a data structure more like:
$array = array(
array('a' => 1),
array('b' => 2)
array('d' => 4)
);
Then, use array_splice($array, 2, 0, array('c' => 3)) to insert at position 2. See manual on array_splice.
An alternative approach is to supplement the associative array structure with an ordered index that determines the iterative order of keys. For instance:
$index = array('a','b','d');
// Add new value and update index
$array['c'] = 3;
array_splice($index, 2, 0, 'c');
// Iterate the array in order
foreach $index as $key {
$value = $array[$key];
}
You can define your own sortmap when doing a bubble-sort by key. It's probably not terribly efficient but it works.
<pre>
<?php
$array = array('a'=>1,'z'=>2,'d'=>4);
$array['c'] = 3;
print_r( $array );
uksort( $array, 'sorter' );
print_r( $array );
function sorter( $a, $b )
{
static $ordinality = array(
'a' => 1
, 'c' => 2
, 'z' => 3
, 'd' => 4
);
return $ordinality[$a] - $ordinality[$b];
}
?>
</pre>
Here's an approach based on ArrayObject using this same concept
$array = new CitizenArray( array('a'=>1,'z'=>2,'d'=>4) );
$array['c'] = 3;
foreach ( $array as $key => $value )
{
echo "$key: $value <br>";
}
class CitizenArray extends ArrayObject
{
static protected $ordinality = array(
'a' => 1
, 'c' => 2
, 'z' => 3
, 'd' => 4
);
function offsetSet( $key, $value )
{
parent::offsetSet( $key, $value );
$this->uksort( array( $this, 'sorter' ) );
}
function sorter( $a, $b )
{
return self::$ordinality[$a] - self::$ordinality[$b];
}
}
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.
// replace value into the original array
function insert_key_before_inplace(&$base, $beforeKey, $newKey, $value) {
$index = 0;
foreach($base as $key => $val) {
if ($key==$beforeKey) break;
$index++;
}
$end = array_splice($base, $index, count($base)-$index);
$base[$newKey] = $value;
foreach($end as $key => $val) $base[$key] = $val;
}
$array = array('a'=>1,'z'=>2,'d'=>4);
insert_key_before_inplace($array, 'z', 'c', 3);
var_export($array); // array ( 'a' => 1, 'c' => 3, 'z' => 2, 'd' => 4, )
// create new array
function insert_key_before($base, $beforeKey, $newKey, $value) {
$index = 0;
foreach($base as $key => $val) {
if ($key==$beforeKey) break;
$index++;
}
$end = array_splice($base, $index, count($base)-$index);
$base[$newKey] = $value;
return $base+$end;
}
$array = array('a'=>1,'z'=>2,'d'=>4);
$newArray=insert_key_before($array, 'z', 'c', 3);
var_export($array); // ( 'a' => 1, 'z' => 2, 'd' => 4, )
var_export($newArray); // array ( 'a' => 1, 'c' => 3, 'z' => 2, 'd' => 4, )
function putarrayelement(&$array, $arrayobject, $elementposition, $value = null) {
$count = 0;
$return = array();
foreach ($array as $k => $v) {
if ($count == $elementposition) {
if (!$value) {
$value = $count;
}
$return[$value] = $arrayobject;
$inserted = true;
}
$return[$k] = $v;
$count++;
}
if (!$value) {
$value = $count;
}
if (!$inserted){
$return[$value];
}
$array = $return;
return $array;
}
$array = array('a' => 1, 'z' => 2, 'd' => 4);
putarrayelement($array, '3', 1, 'c');
print_r($array);
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 :
Select pizza , drink , 'pizza-drink' as 'pizza-drink' , 28 columns..... From Table
Array :
$result['pizza-drink'] = $result['pizza'] . $result['drink'];
A simplified Alix Axel function if you need to just insert data in nth position:
function array_middle_push( array $array, int $position, array $data ): array {
return array_merge( array_slice( $array, 0, $position ), $data, array_slice( $array, $position ) );
}
Try this
$array['c']=3;
An associative array is not ordered by default, but if you wanted to sort them alphabetically you could use ksort() to sort the array by it's key.
If you check out the PHP article for ksort() you will se it's easy to sort an array by its key, for example:
<?php
$fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
ksort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
// The above example will output:
a = orange
b = banana
c = apple
d = lemon
you can add it by doing
$array['c']=3;
and if you absolutely want it sorted for printing purposes, you can use php's ksort($array) function
if the keys are not sortable by ksort, then you will have to create your own sort by using php's uasort function. see examples here
http://php.net/manual/en/function.uasort.php

Categories