I'm struggling on a multidimensional arrays ...
I have merged to arrays and I should assign to them a new value which should be used as a key:
$content = array();
$content[0]['text'] = 'xxxxx';
$content[0]['order']=1
$content[1]['text'] = 'yyyy';
$content[1]['order']=3
$content[2]['text'] = 'yyyyddd';
$content[2]['order']=2
I need to reorder this array by content['order'] values and I'm struggling here.
Please, I'd really need a help here .
Try using usort:
function sort_orders($a, $b) {
if($a['order'] == $b['order'])
{
return 0;
}
return ($a['order'] < $b['order']) ? -1 : 1;
}
usort($content, "sort_orders");
You can do it with usort() and a compare function, like so:
function cmp($a, $b) {
if ($a['order'] == $b['order']) {
return 0;
}
return ($a['order'] < $b['order']) ? -1 : 1;
}
usort($content, 'cmp');
Related
Say I have an array
$ar = ['apples','blueberries','end','pears','dragonfruit','oranges','start','durian','lychee','rambutan','pineapple','end','start'];
I want the array in some order (lets say alphabetic order for this argument), but with the values 'end' on the tail and 'start' on the head of the array.
function cmp($a,$b) {
if ($a == $b) return 0;
if ($b === 'start') return 1;
if ($b === 'end') return -1;
return ($a < $b) ? -1 : 1;
}
usort($ar,"cmp");
echo implode(", ", $ar);
How do I sort so that values matching a specific value will end up at the head or tail of the array, but other values will sort based on other criteria (e.g. numeric, alpha, etc)
You can use array_diff with sort, array_push and array_unshift
$elements = ['start','end'];//start & end elements array
$rest = array_diff($ar, $elements);
sort($rest);//Sorting of the rest items
array_push($rest, $elements[1]);//Push end element
array_unshift($rest, $elements[0]);//Push start element
You can use rsort($rest) for descending order.
Live Example : https://3v4l.org/GnotC
Try this
$ar = ['apples','blueberries','end','pears','dragonfruit','oranges','start','durian','lychee','rambutan','pineapple','end','start', 'end', 'banana', 'yellow'];
function cmp($a, $b) {
if ($a === $b) {
return 0;
}
if ($a === 'start' || $b === 'end' ) {
return -1;
}
if( $b === 'start' || $a === 'end') {
return 1;
}
return ($a < $b) ? -1 : 1; }
usort($ar,"cmp");
echo implode(', ', $ar);
Hope this will help you
Following is how your cmp function should be. Just a couple of if statements introduced.
function cmp($a, $b) {
if ($a === $b) {
return 0;
}
if ($a === 'start' ) {
return -1;
}
if( $b === 'start' ) {
return 1;
}
if ($a === 'end' ) {
return 1;
}
if ($b === 'end' ) {
return -1;
}
return ($a < $b) ? -1 : 1;
}
My question is : is there a function that return next object in array (with array and current object param) ?
Can you help me to code the best way ?
function get_next($array, $currentObject) {
.... ?
return $nextObject;
}
function get_next($array, $currentObject) {
$key = array_search($currentObject, $array);
if($key!==false) {
$key++; // Work only on numbers and letter
if(isset($array[$key])) {
return $array[$key];
} else {
return null;
}
} else {
return null;
}
}
Here is my code, this
for($i = 0; $i < count($array) && $array[i] != $currentObject; $i++);
I would not put this into function at all, I would put it were I am calling that function but here is your function:
function get_next($array, $currentObject) {
for($i = 0; $i < count($array) && $array[i] != $currentObject; $i++);
return array[$i];
}
Simple linear and works in any occasion.
I gave an array populated to look like this -
$array = array(
0 => array(2,3,4),
1 => array(2,3,7,6,8),
-- and so on
);
Is there a shorthand in PHP/PHP5.x to accomplish sorting of such an array based on the number of elements in the value to each key of the primary array?
Thanks.
Use usort()
function cmp($a, $b) {
if (count($a) == count($b)) {
return 0;
}
return (count($a) < count($b)) ? -1 : 1;
}
usort($array, "cmp");
Here's a better optimized version of that function (only calling count() twice):
function cmp($a, $b) {
$numA = count($a);
$numB = count($b)
if ($numA == $numB) {
return 0;
}
return ($numA < $numB) ? -1 : 1;
}
I have array returned
$header_html = array(1=>array('width'=>40,
'sort_case'=>23,
'title'=>'AxA'),
2=>array('width'=>50,
'sort_case'=>7,
'title'=>'B2B'),
3=>array('width'=>100,
'sort_case'=>12,
'title'=>'C12')
);
I want to get new array that depend on $header_array=array('AxA','B2B','C12')
for examples:
if have $header_array=array('C12','B2B','AxA').
the new $header_html will be:
$header_html = array(
1=>array('width'=>100,
'sort_case'=>12,
'title'=>'C12'),
2=>array('width'=>50,
'sort_case'=>7,
'title'=>'B2B'),
3=>array('width'=>40,
'sort_case'=>23,
'title'=>'AxA')
);
and so on...
Anybody know how to do this?
You can sort the array with a custom comparison function using usort:
function cmp($a, $b) {
// Sort via $a['title'] and $b['title']
}
usort($header_html, 'cmp');
The trick is coming up with a comparison function that does what you want. To simply sort backwards by title, you could use:
function cmp($a, $b) {
if ($a['title'] == $b['title'])
return 0;
// usually return -1 if $a < $b, but we're sorting backwards
return ($a['title'] < $b['title'] ? 1 : -1;
}
In PHP 5.3, you can easily do this with a functor and usort.
class MyComparator {
protected $order = array();
public function __construct() {
$values = func_get_args();
$i = 0;
foreach($values as $v) {
$this->order[$v] = $i;
$i++;
}
}
public function __invoke($a, $b) {
$vala = isset($this->order[$a['title']]) ?
$this->order[$a['title']] : count($this->order);
$valb = isset($this->order[$b['title']]) ?
$this->order[$b['title']] : count($this->order);
if($vala == $valb) return 0;
return $vala < $valb ? -1 : 1;
}
}
You can use it like that:
$sorter = new MyComparator('CCC', 'AAA', 'BBB');
usort($header_html, $sorter);
You need a user-defined sort so you can access individual fields of the elements to sort:
function mysort($a, $b)
{
global $header_array;
$pos1 = array_search($a["title"], $header_array);
$pos2 = array_search($b["title"], $header_array);
if ($pos1 == $pos2) { return 0; }
return $pos1 < $pos2 ? -1 : 1;
}
$header_array = array("CCC", "BBB", "AAA");
usort($header_html, "mysort");
print_r($header_array);
note: usort() returns true on success or false on failure; it does not return the resorted array.
It sounds like you want a function to return the array elements in the order you specify in $header_array. If so, here's a stab:
function header_resort($header_array, $header_html) {
foreach($header_array as $i => $val) {
foreach($header_html as $obj) {
if( $obj->title == $val )
$header_html_new[$i] = $obj;
}
}
return $header_html_new;
}
Say I have this array:
$array[] = 'foo';
$array[] = 'apple';
$array[] = '1234567890;
I want to get the length of the longest string in this array. In this case the longest string is 1234567890 and its length is 10.
Is this possible without looping through the array and checking each element?
try
$maxlen = max(array_map('strlen', $ary));
Sure:
function getmax($array, $cur, $curmax) {
return $cur >= count($array) ? $curmax :
getmax($array, $cur + 1, strlen($array[$cur]) > strlen($array[$curmax])
? $cur : $curmax);
}
$index_of_longest = getmax($my_array, 0, 0);
No loop there. ;-)
A small addition to the ticket. I came here with a similar problem: Often you have to output just the longest string in an array.
For this, you can also use the top solution and extend it a little:
$lengths = array_map('strlen', $ary);
$longestString = $ary[array_search(max($lengths), $lengths)];
Loop through the arrays and use strlen to verify if the current length is longer than the previous.. and save the index of the longest string in a variable and use it later where you need that index.
Something like this..
$longest = 0;
for($i = 0; $i < count($array); $i++)
{
if($i > 0)
{
if(strlen($array[$i]) > strlen($array[$longest]))
{
$longest = $i;
}
}
}
This way you can find the shortest (or longest) element, but not its index.
$shortest = array_reduce($array, function ($a, $b) {
if ($a === null) {
return $b;
}
return strlen($a) < strlen($b) ? $a : $b;
});