To Sort the Array Independent to dependent values - php

$arr = array("a.test.com","a.b.test.com","b.test.com","a.a.b.test.com","c.test.com");
i need to sort the array as
$arr = array("a.a.b.test.com","a.b.test.com","b.test.com","c.test.com","a.test.com");
So that i can delete the indepentable domain to delete first
Can anyone Help???

There is an example will help you.
$arr = array("a.test.com","a.b.test.com","b.test.com","a.a.b.test.com","c.test.com");
print "<pre>";
print_r($arr);
function domainSort($a, $b) {
list($aMailbox,$aDomain) = explode('.',$a);
list($bMailbox,$bDomain) = explode('.',$b);
if ($aDomain == $bDomain) {
return 0;
}
return ($aDomain < $bDomain) ? -1 : 1;
}
usort($arr,'domainSort');
echo 'Sorted<br />';
print_r($arr);
Output:
Array
(
[0] => a.test.com
[1] => a.b.test.com
[2] => b.test.com
[3] => a.a.b.test.com
[4] => c.test.com
)
Sorted
Array
(
[0] => a.a.b.test.com
[1] => a.b.test.com
[2] => c.test.com
[3] => b.test.com
[4] => a.test.com
)

You can sort by the dot count:
$arr = array("a.test.com","a.b.test.com","b.test.com","a.a.b.test.com","c.test.com");
function cmp($a, $b) {
$aDots = count(explode('.', $a);
$bDots = count(explode('.', $b);
// count dots
if ($aDots > $bDots) {
return 1;
}
else if ($aDots < $bDots) {
return -1;
}
// if equal, do string compare
else {
return strcmp($a, $b);
}
}
usort($arr, "cmp");
Fiddle

Related

PHP sort array substring

I want to sort this array by year:
Array
(
[0] => data/pictures/alice/1980
[1] => data/pictures/alice/1985
[2] => data/pictures/bob/1981
[3] => data/pictures/bob/1985
[4] => data/pictures/bob/1987
[5] => data/pictures/bob/1989
)
Expected result:
Array
(
[0] => data/pictures/alice/1980
[1] => data/pictures/bob/1981
[2] => data/pictures/alice/1985
[3] => data/pictures/bob/1985
[4] => data/pictures/bob/1987
[5] => data/pictures/bob/1989
)
I've already tried different sort functions without success.
Example:
asort($paths, SORT_STRING | SORT_FLAG_CASE);
sort($path, SORT_NUMERIC);
Since it's a path just map the array through basename() and then sort based on that:
array_multisort(array_map('basename', $paths), SORT_ASC, $paths);
Try this
function cmp($a, $b) {
// if equal, don't do much
if ($a == $b) {
return 0;
}
$explodedA = explode('/', $a);
$explodedB = explode('/', $b);
$yearPartA = $explodedA[count($explodedA) - 1];
$yearPartB = $explodedB[count($explodedB) - 1];
if ($explodedPartA == $explodedPartB) { // compare full string
return ($a < $b) ? -1 : 1;
}
return ($yearPartA < $yearPartB) ? -1 : 1;
}
// actual sort of the array $path (e.g. the whole point)
usort($path, "cmp");
Consider, however that you'd probably be doing 'explode' several times for each array element and that it might be cheaper to work a bit on the array first. Not sure how big your array is... Do some testing.
$array = ['data/pictures/alice/1980','data/pictures/alice/1985','data/pictures/bob/1981','data/pictures/bob/1985','data/pictures/bob/1987','data/pictures/bob/1989'];
uasort($array, function($a,$b) {
$y1 = array_pop(explode('/', $a));
$y2 = array_pop(explode('/', $b));
if($y1===$y2) {
// if year the same use other criteria
if($a===$b) {
return 0;
}
return $a>$b?-1:1;
};
return $y1>$y2?-1:1;
});
Use usort and in the custom function explode the strings by "/" and compare the last parts of the arrays.

Not getting how to sort multidimensional array by a specific key in php [duplicate]

This should be really simple, but what is the way to go on this.
I want to sort an multidimensional array by a key, like this:
Array (
[0] => Array
(
[iid] => 1
[invitee] => 174
[nid] => 324343
[showtime] => 2010-05-09 15:15:00
[location] => 13
[status] => 1
[created] => 2010-05-09 15:05:00
[updated] => 2010-05-09 16:24:00
)
[1] => Array
(
[iid] => 1
[invitee] => 220
[nid] => 21232
[showtime] => 2010-05-09 15:15:00
[location] => 12
[status] => 0
[created] => 2010-05-10 18:11:00
[updated] => 2010-05-10 18:11:00
))
Say i want to sort this by [status], how would I achieve this?
Thanks in advance!
//define a comparison function
function cmp($a, $b) {
if ($a['status'] == $b['status']) {
return 0;
}
return ($a['status'] < $b['status']) ? -1 : 1;
}
usort($array, "cmp");
That should do what you want, you can alter the comparison function to sort on whatever key you want.
Try this : Using array_multisort
$sort = array();
foreach($your_array as $k=>$v) {
$sort['status'][$k] = $v['status'];
}
array_multisort($sort['status'], SORT_DESC, $your_array);
echo "<pre>";
print_r($your_array);
Ref: http://php.net/manual/en/function.array-multisort.php
usort function is what you're looking for:
<?php
function cmp($a, $b) {
return $b["status"] - $a["status"];
}
$sorted = usort($your_array, "cmp");
var_dump($sorted);
?>
Try this
function cmp_by_status($a, $b)
{
if ($a['status'] == $b['status']) {
return 0;
}
return ($a['status'] < $b['status') ? -1 : 1;
}
usort($data_array, "cmp_by_status");
I have added this answer at Sort multi-dimensional array by specific key sort the array specific key to sorting array value.
function sortBy($field, &$array, $direction = 'asc')
{
usort($array, create_function('$a, $b', '
$a = $a["' . $field . '"];
$b = $b["' . $field . '"];
if ($a == $b)
{
return 0;
}
return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
'));
return true;
}
Call this function by specific array key
sortBy('status', $array);

Merging array in recursive function using php?

After one week searching and converting many algorithm from other language into php to make an array that contain "combination k from n". I'm stuck.
please help me.
This is my code (using php):
function comb($item,$arr,$out, $start, $n, $k, $maxk) {
if ($k > $maxk) {
foreach($arr as $ar){
echo "$ar";
echo "<br/>";
}
return;
}
for ($i=$start; $i<=$n; $i++) {
$arr[$k] = $item[$i-1];
comb($isi, $arr, $out, $i+1, $n, $k+1, $maxk);
}
}
$team = array("A","B","C","D");
$ar = array();
$o = array();
comb($team,$ar,$o,1,4,1,2);
Recursive algorithm above is really confuse me. The code above was successful to form the combination but I cannot merge them into one array because of its recursive characteristics. I just want to make an array that contain the result of combination of 2 from 4 items. Like this (see below)
Array (
[0] => Array (
[1] => A
[2] => B
)
[1] => Array (
[1] => A
[2] => C
)
[2] => Array (
[1] => A
[2] => D
)
[3] => Array (
[1] => B
[2] => C
)
[4] => Array (
[1] => B
[2] => D
)
[5] => Array (
[1] => C
[2] => D
)
)
I know I still far from the answer. But please guide me, to reach that answer. Perhaps you know the other technique, it doesn't matter. If your code works, I will use it. No matter what the technique you've used. Any ideas would be gratefully appreciated,Thank you..!
An (I think) simpler recursive implementation is:
<?php
/* Given the array $A, returns the array of $k-subsets
of $A in lexicographical order. */
function k_lex_subset($A,$k) {
if (($k <= 0) or (count($A) < $k)) { return array(); }
else if ($k <= 1) { return array_chunk($A,1); }
else {
$v = array_shift($A);
$AwA = k_lex_subset($A,$k-1);
foreach($AwA as &$vp) {
array_unshift($vp,$v);
}
$AwoA = k_lex_subset($A,$k);
$resultArrs = array_merge($AwA, $AwoA);
return($resultArrs);
}
}
$team = array("A","B","C","D");
print_r(k_lex_subset($team,2));
?>
which returns
Array
(
[0] => Array
(
[0] => A
[1] => B
)
[1] => Array
(
[0] => A
[1] => C
)
[2] => Array
(
[0] => A
[1] => D
)
[3] => Array
(
[0] => B
[1] => C
)
[4] => Array
(
[0] => B
[1] => D
)
[5] => Array
(
[0] => C
[1] => D
)
)
and will work for any size array, and any $k.
The term you are looking for is (lexicographical) k-subset enumeration where $k is 2 in this specific case.
Explanation
The idea is very simple. Assume we have (for example) a set {A,B,C,D}. We want to start with all sets with A in, and so we consider subsets of size 1-less coming from {B,C,D} and append A to them yielding
{{A,B}, {A,C}, {A,D}}
and then we consider all subsets of size 2 without A in
{{B,C}, {B,D}, {C,D}}
and then we just merge the two. It is hopefully easy to see how, in general, this yields a nice recursive strategy for constructing the k-subsets of a set (instead of just k=2).
Reference
A fantastic reference on this sort of thing is Vol 4 Fasicle 3 of Knuth's The Art of Computing Programming.
This should do the trick to reach the array you've described above:
<?php
$array = array("A","B","C","D");
function transformArray( $array ) {
$returnArray = array();
for( $i=0; $i < count($array); $i++ ) {
for( $j=$i+1; $j < count($array); $j++ ) {
$returnArray[] = array( $array[$i], $array[$j] );
}
}
return $returnArray;
}
print_r(transformArray($array));
?>
Not exactly sure on the necessity of start, n, and k, but this should get you the expected output. If you provide some more details on why those counters would be necessary, we can get you a more thorough answer.
function comb($itemArray, $start, $n, $k, $maxk) {
//if ($k > $maxk) return;
$outputArray = array();
foreach($itemArray AS $index => $firstChar) {
for($i = $index+1; $i<count($itemArray); $i++) {
$secondChar = $itemArray[$i];
$outputArray[] = array($firstChar, $secondChar);
}
}
return $outputArray;
}
$teamArray = array("A","B","C","D");
$resultArray = comb($teamArray,1,4,1,2);
ppr($resultArray);
function ppr($variable) {
echo '<pre>';
print_r($variable);
echo '</pre>';
}
function comb($a, $len){
if ($len > count($a))return array();
$out = array();
if ($len==1) {
foreach ($a as $v) $out[] = array($v);
return $out;
}
$len--;
while (count($a) > $len) {
$b = array_shift($a);
$c = comb($a, $len);
foreach ($c as $v){
array_unshift($v, $b);
$out[] = $v;
}
}
return $out;
}
$test = array('a','b','c','d');
$a = comb($test,2);
print_r($a);
would give you:
Array(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => a
[1] => c
)
[2] => Array
(
[0] => a
[1] => d
)
[3] => Array
(
[0] => b
[1] => c
)
[4] => Array
(
[0] => b
[1] => d
)
[5] => Array
(
[0] => c
[1] => d
)
)
Why are you doing
echo "ar"
instead of
echo $ar
Also are you looking for permutation or combination? Here is a site with very nice algorithms for both. The implementation is in java but it's very clear. so converting to php won't be difficult: http://geekviewpoint.com/Numbers_functions_in_java/
If you want a pure clean recursive way use this:
function comb($item, $n) {
return comb_rec($item, array(), $n);
}
function comb_rec($items, $c, $n) {
if (count($c) == $n) {
return array($c);
}else{
if (count($items) == 0) {
return $items;
}else{
$list = $items;
$head = array_shift($list);
$tail = $list;
$current = $c;
array_push($current,$head);
return array_merge(comb_rec($tail, $current, $n),comb_rec($tail, $c, $n));
}
}
}
$team = array("A","B","C","D");
$all = comb($team,2);
print_r($all);

Sort array by key value

So I have this array.
Array
(
[0] => Array
(
[key_1] => something
[type] => first_type
)
[1] => Array
(
[key_1] => something_else
[type] => first_type
)
[2] => Array
(
[key_1] => something_else_3
[type] => second_type
)
[3] => Array
(
[key_1] => something_else_4
[type] => second_type
)
)
I have to sort by type value in a pattern like this:
first_type
second_type
first_type
second_type
My questions is, how can I do this?
Thanks a lot!
You need to use usort with a custom comparison function that compares the key_1 sub-keys of each item (you can use strcmp to do this conveniently). Assuming you do not want to change the structure of the resulting array, it would look something like this:
$arr = /* your array */
usort($arr, function($a, $b) { return strcmp($a['key_1'], $b['key_1']); });
So here's how I got it to work:
function filter_by_value($array, $index, $value) {
if(is_array($array) && count($array) > 0) {
foreach(array_keys($array) as $key){
$temp[$key] = $array[$key][$index];
if ($temp[$key] == $value){
$newarray[$key] = $array[$key];
}
}
}
return $newarray;
}
$array = /* array here */
$type1 = array_values(filter_by_value($array, 'type', '1'));
$type2 = array_values(filter_by_value($array, 'type', '2'));
$i = 1; $x = 1; $y = 1;
$sorted = array();
foreach ($array as $a) {
if ($i % 2) {
$sorted[$i-1] = $type1[$x-1];
$x++;
} else {
$sorted[$i-1] = $type2[$y-1];
$y++;
}
$i++;
}
Found filter_by_value() on php.net but I don't remember where so, that's not made by me.
Maybe this is not the best solution but it works pretty fine.
If sort() and its relevant alternatives don't work you will have to use usort() or uasort() with a custom function to sort this array.

How to sort a multidimensional array by a certain key?

This should be really simple, but what is the way to go on this.
I want to sort an multidimensional array by a key, like this:
Array (
[0] => Array
(
[iid] => 1
[invitee] => 174
[nid] => 324343
[showtime] => 2010-05-09 15:15:00
[location] => 13
[status] => 1
[created] => 2010-05-09 15:05:00
[updated] => 2010-05-09 16:24:00
)
[1] => Array
(
[iid] => 1
[invitee] => 220
[nid] => 21232
[showtime] => 2010-05-09 15:15:00
[location] => 12
[status] => 0
[created] => 2010-05-10 18:11:00
[updated] => 2010-05-10 18:11:00
))
Say i want to sort this by [status], how would I achieve this?
Thanks in advance!
//define a comparison function
function cmp($a, $b) {
if ($a['status'] == $b['status']) {
return 0;
}
return ($a['status'] < $b['status']) ? -1 : 1;
}
usort($array, "cmp");
That should do what you want, you can alter the comparison function to sort on whatever key you want.
Try this : Using array_multisort
$sort = array();
foreach($your_array as $k=>$v) {
$sort['status'][$k] = $v['status'];
}
array_multisort($sort['status'], SORT_DESC, $your_array);
echo "<pre>";
print_r($your_array);
Ref: http://php.net/manual/en/function.array-multisort.php
usort function is what you're looking for:
<?php
function cmp($a, $b) {
return $b["status"] - $a["status"];
}
$sorted = usort($your_array, "cmp");
var_dump($sorted);
?>
Try this
function cmp_by_status($a, $b)
{
if ($a['status'] == $b['status']) {
return 0;
}
return ($a['status'] < $b['status') ? -1 : 1;
}
usort($data_array, "cmp_by_status");
I have added this answer at Sort multi-dimensional array by specific key sort the array specific key to sorting array value.
function sortBy($field, &$array, $direction = 'asc')
{
usort($array, create_function('$a, $b', '
$a = $a["' . $field . '"];
$b = $b["' . $field . '"];
if ($a == $b)
{
return 0;
}
return ($a ' . ($direction == 'desc' ? '>' : '<') .' $b) ? -1 : 1;
'));
return true;
}
Call this function by specific array key
sortBy('status', $array);

Categories