PHP sort not working [duplicate] - php

This question already has answers here:
Sort array not working
(2 answers)
Closed 10 months ago.
I'm trying to sort a string alphabetically. I thought I could explode a string into an array and sort it, but the echo is returning nothing.
$schools = "high*low*other*";
$schools = explode("*", $schools);
$schools = sort($schools);
echo $schools[0];

sort() sorts in place (i.e. modifies the array itself A.K.A. the $schools variable is passed by reference) so no array is returned. A boolean value is however returned to determine if the sort was successful.
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
$schools = "high*low*other*";
$schools = explode("*", $schools);
sort($schools);
echo $schools[0];

Your problem can be solved by the following code example:
<?php
$schools = "c*d*a";
$alpha_sorted_array = explode("*", $schools);
sort($alpha_sorted_array);
foreach($alpha_sorted_array as $itemToPrint){
echo("Item: $itemToPrint\n");
}
?>
Basically, you reasign what happens when you use the explode function on the string variable held inside schools, as you know, explode uses the first delimiter, in this case * found inside the initial string $schools to return an array. From this point you can call the sort function on the new array and it will return a sorted array(no resasinging needed for this one, just call sort() on it)
The given output is:
Item: a
Item: c
Item: d

The solution is natcasesort
This function sorts values with natural algorithm and case-insensitively.

Related

Array is not getting sorted with sort() function PHP [duplicate]

This question already has answers here:
Sort array not working
(2 answers)
Closed 10 months ago.
I'm trying to sort an array numerically. Here's my code
<?php
$data = '9#Saul,7#Jesse,1#Skyler,6#Walter';
$exp = explode(",",$data);
$expsort = sort($exp);
print_r($expsort);
?>
But it is not working. The output is showing only "1".
You are assigning the value of the sort function -which sorts the argument array itself, and it always returns true and thus you got 1 as a result.
So if you print your original exploded array, it will be sorted. Please note, sort overrides your original array
$data = '9#Saul,7#Jesse,1#Skyler,6#Walter';
$exp = explode(",",$data);
sort($exp);
print_r($exp);

Get value of previous array key [duplicate]

This question already has answers here:
PHP get previous array element knowing current array key
(10 answers)
Closed 4 years ago.
So I tried doing this :
$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
var_dump(prev($array["second"]));
Hoping to get 111 but I get NULL. Why?
$array["second"] returns 222. Shouldn't we get 111 when we use PHP's prev() function?
How to get the previous value of an array if it exists using the key?
Your current value from $array["second"] is not an array and prev takes an array as a parameter.
You have to move the internal pointer of the $array and then get the previous value.
$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
while (key($array) !== "second") next($array);
var_dump(prev($array));
prev function expects an array as an argument but you're passing a string.
$array["second"] evaluates to '222'
In this case, you point directly the previous value, without iterating the array.
$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
$keys = array_flip(array_keys($array));
$values = array_values($array);
var_dump($values[$keys['second']-1]);

loop through a multi-dimensional array and echo the value in PHP [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I have a multi-dimensional array that takes the form:
array = [value1, some number],[value2, some number]...
I need to loop through the array and echo the value followed by a tokenizer so the final output looks like:
value1!##$value2!##$
I know that I have to concatenate the return value with ."!##$" but I do not know how to loop through the array. Can anyone offer some help.
My array is being made from a MySQL Query as follows:
while($row = $results -> fetch_assoc()) {
$return_array[] = array(
$row['uid'],($row['column1] - $row['column2']));
}
Then I am perfoming a usort on the array
To be simple enough, you can use implode and array_column:
$array = [['value1', 123], ['value2', 234]];
echo implode('!##$', array_column($array, 0)) . '!##$';
This gives:
value1!##$value2!##$
Explanation:
implode - Joins array values using some specified value, here !##$
array_column - implode accepts one dimensional array, also you want only the first index of the array to be joined, so creating an array with just first index.

How to merge two two dimensional arrays with the same number of elements per sub array in php?

I need to merge the second array into the first. For example the first array is
$data_array = array
(
array('Ford','Escape','25000','new')
);
The second array is
$new_array = array
(
array('Toyota','Camry','12000','used')
);
For merging the two arrays I tried
$data_array = array_merge($data_array[0],$new_array[0]);
print_r($data_array);
This combines the two arrays into one row array. What I want is to create two rows, each containing one of those arrays.
Sample result:
array(array('Ford','Escape','25000','new'),array('Toyota','Camry','12000','used'))
You have to assign the merged result. Pay attention to the function signature and description in the manual for array_merge():
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
$merged_array = array_merge($data_array[0],$new_array[0]);
print_r($merged_array);
You could call it $data_array and overwrite the existing one:
$data_array = array_merge($data_array[0],$new_array[0]);
print_r($data_array);
Or even $data_array[0]:
$data_array[0] = array_merge($data_array[0],$new_array[0]);
print_r($data_array);
Contrast this with something like sort():
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
Where the bool means that it returns true or false and the & preceding $array means that the array is passed by reference and modified.
However, after your edit it seems that you want the two rows in your original arrays to be two rows in a new array, so just don't specify the index [0]:
$data_array = array_merge($data_array,$new_array);
print_r($data_array);

ksort-ing an array of array using array_walk in PHP?

How can apply ksort to each element of $counts array? I mean simply call this function on each nested array, not recursively.
bool array_walk(array &$array, callable $funcname [,mixed $userdata = NULL])
I've tried array_walk passing the flag SORT_NUMERIC as user data. This gives me a warning:
$counts = array();
$counts['group1'] = array(); // Keys are timestamps but as STRING
$counts['group2'] = array(); // Keys are timestamps but as STRING
// ...
// Array + operator does a key reordering here
$counts['group1'] += $dummyData;
$counts['group2'] += $dummyData;
// .. so sort array by keys
array_walk($counts, 'ksort', SORT_NUMERIC);
Warning: ksort() expects at most 2 parameters, 3 given.
What's the third parameter?
EDIT: genius answer:
foreach($counts as &$group) :
ksort($group, SORT_NUMERIC);
endforeach;
From http://php.net/manual/en/function.array-walk.php
Typically, funcname takes on two parameters. The array parameter's
value being the first, and the key/index second.
If the optional userdata parameter is supplied, it will be passed as
the third parameter to the callback funcname.

Categories