Custom sort of an array - php

I'm having an array of data like this:
$array = array(
'total_ids' => 0,
'unique_ips' => 0,
'unique_ids' => 0,
'global' => 0,
'total_ips' => 0,
);
I need it to be sorted to this:
$array = array(
'unique_ids' => 0,
'unique_ips' => 0,
'total_ids' => 0,
'total_ips' => 0,
'global' => 0
);
I believe this can be done via uksort, but i can't find the solution of custom_sort function.

This seems rather pointless, can you provide a reason why you need this? I assume it's something to do with a looped output.
$new_array = array(
'unique_ids' => $array['unique_ids'],
'unique_ips' => $array['unique_ips'],
'total_ids' => $array['total_ids'],
'total_ips' =>$array['total_ips'],
'global' => $array['global']
);
$array = $new_array;

It looks like the sorting is done by string length, then by alphabetical ordering. That's not too hard to accomplish using uksort!
function cmp( $a, $b)
{
if( strlen( $a) != strlen( $b))
{
return strlen( $a) < strlen( $b) ? 1 : -1;
}
return strcasecmp( $a, $b);
}
uksort( $array, 'cmp');
Output:
// Before uksort()
array(5) {
["total_ids"]=>
int(0)
["unique_ips"]=>
int(0)
["unique_ids"]=>
int(0)
["global"]=>
int(0)
["total_ips"]=>
int(0)
}
// After uksort()
array(5) {
["unique_ids"]=>
int(0)
["unique_ips"]=>
int(0)
["total_ids"]=>
int(0)
["total_ips"]=>
int(0)
["global"]=>
int(0)
}
See the magic.

I have a set of such arrays but not sorted. I'll be inserting the values to the database with a single query, like INSERT INTO table (unique_ids,unique_ips,total_ids,total_ips,global) VALUES (...),(...),(...) etc. Thats why i need the arrays of this set to be sorted identically
So why not do something like
$array = array(
'total_ids' => 0,
'unique_ips' => 0,
'unique_ids' => 0,
'global' => 0,
'total_ips' => 0,
);
'INSERT INTO table(' . implode(', ', array_keys($array)) . ') VALUES (' . implode(', ', $array) . ')'
Quickly typed it, expect some syntax errors.

This will sort the array descending based on the array key
You want to sort the array descending so you can use this function krsort which will sort the array based on the key descending and I will put them in new array named sorted array
<?php
$array = array(
'total_ids' => 0,
'unique_ips' => 0,
'unique_ids' => 0,
'global' => 0,
'total_ips' => 0,
);
krsort($array);
$sorted_array = array();
foreach ($array as $key => $value) {
$sorted_array[$key] = $value;
}
print_r($sorted_array);
?>

Related

How to check the key of next index of arrays in PHP?

I have an PHP array :
$datas = array(
"abcd" => array(
"1639340364" => 1,
"1639362752" => 85,
"1639363500" => 74,
),
"efgh" => array(
"1639340364" => 78,
"1639362754" => 98,
"1639363500" => 46,
),
"ijkl" => array(
"1639340364" => 78,
"1639362754" => 98,
"1639363505" => 46,
),
);
I want to check the keys of each array and if not match need to add it on every array.
Expecting output like:
$datas = array(
"abcd" => array(
"1639340364" => 1,
"1639362752" => 85,
"1639362754" => 0,
"1639363500" => 74,
"1639363505" => 0,
),
"efgh" => array(
"1639340364" => 78,
"1639362752" => 0,
"1639362754" => 98,
"1639363500" => 46,
"1639363505" => 0,
),
"ijkl" => array(
"1639340364" => 78,
"1639362752" => 0,
"1639362754" => 98,
"1639363500" => 0,
"1639363505" => 46,
),
);
If the key is not exist need to add the key with value zero. Is that possible?
I tried with array_key_exists() function...
But I'm not sure where I want to check, when I'm checking It's return true(1). I know it's checking on the same array, Actually I want to know where I will check the condition?
foreach($datas as $key => $data ){
print_r($data);
foreach($data as $key => $point ){
$val = array_key_exists($key,$data);
echo $val;
}
}
I came up with this:
// prepare default keys
$keys = [];
foreach ($datas as $data) {
$keys = array_merge($keys, array_keys($data));
}
$keys = array_unique($keys);
sort($keys);
// construct default array with zeros
$default = array_combine($keys, array_fill(0, count($keys), 0));
// insert the default array
foreach ($datas as $key => $data) {
$datas[$key] = array_replace($default, $data);
}
// show result
echo '<pre>';
print_r($datas);
echo '</pre>';
I needed used a plethora of array functions. The idea is this: First I gather all the possible 'keys' from the array, make them unique, sort them and combine them into a new 'default' array containing only zero values. After that I use the array_replace() function to insert this array into the existing $datas array. This function does exactly what you want:
array_replace() replaces the values of array with values having the
same keys in each of the following arrays. If a key from the first
array exists in the second array, its value will be replaced by the
value from the second array.
It's not pretty or optimised, but here you go:
$subkeys = array();
foreach ($datas as $k => $d) {
foreach($d as $k2 => $d2) {
$subkeys[$k2] = 0;
}
}
foreach ($datas as $k => &$d) {
foreach ($subkeys as $xk => $xd) {
if ( ! array_key_exists($xk, $d)) {
$d[$xk] = $xd;
}
}
}

Array slice like hash slice in perl

Is there built-in function, or shorter way to extract elements into new array, as described here?
<?php
function arr_slice ($arr, $keys) {
$ret = array();
foreach ($keys as $k) { $ret[$k] = $arr[$k]; }
return $ret;
}
$array = array(
"a" => 1,
"b" => 2,
"c" => 3,
"d" => 4,
);
var_export(
arr_slice($array, array("x","d","b"))
);
output (key order matters)
array (
'x' => NULL,
'd' => 4,
'b' => 2,
)

PHP: Get the keys with the longest string in an associative array

I want to first get the keys with the same values and then keep the keys with the longest string. Here is the code compiled so far:
<?php
$data = array('Anna' => 1, 'Ann' => 1, 'Tommy' => 100, 'Tom' => 100);
$total = array_count_values($data);
$filtered = array_filter($data, function ($value) use ($total) {
return $total[$value] > 1;
});
print_r($filtered);
?>
The current output:
Array ( [Anna] => 1 [Ann] => 1 [Tommy] => 100 [Tom] => 100 )
My expected output:
Array ( [Anna] => 1 [Tommy] => 100)
Many thanks for help.
Not necessarily the most optimized solution, but you could write it up using simple check:
$data = array('Anna' => 1, 'Ann' => 1, 'Tommy' => 100, 'Tom' => 100, 'Dan' => 200, 'Danny' => 200);
$total = array_count_values($data);
$filtered = array_filter($data, function ($value) use ($total) {
return $total[$value] > 1;
});
foreach($data as $key => $value) {
$foundKey = array_search($value,$filtered);
if($foundKey){
if(strlen($foundKey) < strlen($key)){
unset($filtered[$foundKey]);
} elseif(strlen($foundKey) > strlen($key)) {
unset($filtered[$key]);
}
}
}
print_r($filtered);
Not sure to post it after even answer is accepted but I have simple hack for this using ksort() and array_flip():
$data = array('Anna' => 1, 'Ann' => 1, 'Tommy' => 100, 'Tom' => 100, 'Dan' => 200, 'Danny' => 200);
ksort($data);
$result=array_flip(array_flip($data));
print_r($result);
ksort(): Sort an array by key
array_flip(): Flip all keys with their associated values in an array
Demo

Moving array element to top in PHP

$arr = array(
'a1'=>'1',
'a2'=>'2'
);
I need to move the a2 to the top, as well as keep the a2 as a key how would I go on about it I can't seem to think a way without messing something up :)
Here is a solution which works correctly both with numeric and string keys:
function move_to_top(&$array, $key) {
$temp = array($key => $array[$key]);
unset($array[$key]);
$array = $temp + $array;
}
It works because arrays in PHP are ordered maps.
Btw, to move an item to bottom use:
function move_to_bottom(&$array, $key) {
$value = $array[$key];
unset($array[$key]);
$array[$key] = $value;
}
You can achieve that this way:
$arr = array(
'a1'=>'1',
'a2'=>'2'
);
end($arr);
$last_key = key($arr);
$last_value = array_pop($arr);
$arr = array_merge(array($last_key => $last_value), $arr);
/*
print_r($arr);
will output (this is tested):
Array ( [a2] => 2 [a1] => 1 )
*/
try this:
$key = 'a3';
$arr = [
'a1' => '1',
'a2' => '2',
'a3' => '3',
'a4' => '4',
'a5' => '5',
'a6' => '6'
];
if (isset($arr[ $key ]))
$arr = [ $key => $arr[ $key ] ] + $arr;
result:
array(
'a3' => '3',
'a1' => '1',
'a2' => '2',
'a4' => '4',
'a5' => '5',
'a6' => '6'
)
Here's a simple one liner to get this done with array_splice() and the union operator:
$arr = array('a1'=>'1', 'a2'=>'2', 'a3' => '3');
$arr = array_splice($arr,array_search('a2',array_keys($arr)),1) + $arr;
Edit:
In retrospect I'm not sure why I wouldn't just do this:
$arr = array('a2' => $arr['a2']) + $arr;
Cleaner, easier and probably faster.
You can also look at array_multisort This lets you use one array to sort another. This could, for example, allow you to externalize a hard-coded ordering of values into a config file.
<?php
$ar1 = array(10, 100, 100, 0);
$ar2 = array(1, 3, 2, 4);
array_multisort($ar1, $ar2);
var_dump($ar1);
var_dump($ar2);
?>
In this example, after sorting, the first array will contain 0, 10, 100, 100. The second array will contain 4, 1, 2, 3. The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well.
Outputs:
array(4) {
[0]=> int(0)
[1]=> int(10)
[2]=> int(100)
[3]=> int(100)
}
array(4) {
[0]=> int(4)
[1]=> int(1)
[2]=> int(2)
[3]=> int(3)
}

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