<?php
foreach ($jsonObj as $items) {
foreach ($items["items"] as $itemlist){
// $itemlist['position']; I want them to echo in that order
echo $itemlist['name'];
}
}
?>
I have an array that I loop through. In that array there is name and order. I would like to display them in numerical order, how can I make it print out the itemlist with lowest number first, then the second etc?
You can use usort with cmp_function for this. Try this function:
function compare_position($a, $b) {
return $a['position'] - $b['position'];
}
Then when you are iterating through the array:
foreach ($jsonObj as $items) {
usort($items['items'], "compare_position");
foreach ($items["items"] as $itemlist){
echo $itemlist['position'];
echo $itemlist['name'];
}
}
More about usort can be found here http://php.net/manual/en/function.usort.php
Hope this helps :)
You need to prepare an array of the positions to sort on first. Sort then sorts by reference allowing you to loop through it a second time but this time as sorted by array_multisort().
<?php
foreach($jsonObj as $items) {
foreach($items['items'] as $key => $itemlist) {
$positions[$key] = $itemlist['position'];
$names[$key] = $itemlist['name'];
}
array_multisort($positions, SORT_ASC, $items['items']);
foreach($items['items'] as $itemlist) {
echo $itemlist['name'], "<br />";
// Now in asc order of positions
}
}
The advantage of this is if other attributes come along that you want to sort on you can do that. For example if there's a chance 'position' will be the same for two people, you could then sort alphabetically by their name etc..
Full solution on Codepad, two answers compared:
http://codepad.viper-7.com/5yJ72S
Related
We have two array variables with names first_names and last_names that have an uncertain number of members. We intend to select an appropriate loop and only use the same information loop with the corresponding first and second variable information respectively.
You must use a loop.
<؟php
$first_names=array('jack','root','admin');
$last_names=array('jack111','root222','admin333'');
foreach (array_combine($first_names ,$last_names) as $fname => $lname)
{
print_r($fname.$lname."<br>");
};
?>
Try this. Simple n easy to understand
$first =count($first_names);
$last =count($last_names);
for($i=1;i<=$first;$i++)
{
echo $i;
}
for($i=1;i<=$last;$i++)
{
echo $i;
}
I have a script that sorts input taking into account parent-child relations and the given display-order of each. A simplified array could look like this (the actual array has sub-arrays for children as well)
$output = Array
(
[7] => first array
[3] => second array
[1] => last array
)
In which the keys are the correspondings id's of the input. Now I wish to pass through this array from top to bottom in a while loop. I am not using foreach because if it has children multiple elements should be processed together, and not come again in the next 'loop'.
function recursive_func($array){
while ($i<=count($array)){
if (isset($array[$i]['children'])){
?><div><?php
recursive_function($array[$i]['children']);
$i++;
recursive_function($array[$i]['children']);
$i++;
?></div><?php
}
else{
?><div>Something</div><?php
$i++;
}
}
}
Clearly $array[$i]['children'] aren't the children of the i'th element (by position), but of the key with value i.
How can I pass through this array in the order as in $output?
You can use array_keys to get the keys in sorted order, and iterate through those.
Or can also use array_values, then you can index sequentially. Just do it right at the start.
function recursivefunction( $array ) {
$array = array_values($array);
....
}
I'm not sure why one entry having children means the next does as well, but I'll assume foreach is problematic.
Since the $output keys are not in order, one way is to do the following:
First get all the array keys:
$keys=array_keys($output);
Next, you may call the recursive_func($keys,$output):
function recursive_func($keys,$output){
$size=count($keys);
$i=0;
while ($i<=$size){
if (isset($output[$i]['children'])){
?><div><?php
$a=$output[$i]['children'];
recursive_function(array_keys($a),$a);
$i++;
$a=$output[$i]['children'];
recursive_function(array_keys($a),$a);
$i++;
?></div><?php
}
else{
?><div>Something</div><?php
$i++;
}
}
}
Please note that it is better that you set the $size of the array outside of the loop for better performance
As Garr Godfrey suggested, you can solve this with array_keys() like so
function recursive_func($array){
$keys = array_keys($array);
for ($i=0; $i<count($keys); $i++) {
if (isset($array[ $keys[$i] ]['children'])) {
recursive_func($array[ $keys[$i] ]['children']);
$i++;
recursive_func($array[ $keys[$i] ]['children']);
} else {
//sth, no $i++ here!
}
}
}
Because I am using a for loop here, the $i++ inside the loop will make it possible for you to skip one element
I have an array, I need to loop through and change it's value:
foreach ($input['qualification'] as &$_v) {
$_v = ucwords($_v);
}
But this only works for the first item in the array. When I remove the ampersand it loops through the entire array, but obviously the changes are not made.
If you're trying to apply a function to all of the values in an array I would recommend using array_map() instead.
Applies the callback to the elements of the given arrays
$qualifications = array_map('ucwords', $input['qualification']);
Demo
$input['qualification'] = array('high school', 'inter school', 'bachelor of scinece', 'master of science');
foreach ($input['qualification'] as &$_v) {
$_v = ucwords($_v);
}
echo "<pre>";print_r($input['qualification']);
Here is how to do it more slowly, with explicit reference to the index, in case your actual programming task requires the value of the index.
https://eval.in/436395
$input = array('juggling','french','math');
foreach ($input as $i=>$v) {
$input[$i] = ucwords($v);
}
I'm using shuffle() to randomly generate items on my site like so:
shuffle($items);
$shirts = array();
foreach ($items as $key => &$row) {
$shirts[$row['Id']] = $row['shirts'];
}
The code goes further, but basically it's running a foreach and displays 12 results. However, shuffle() seems to only return the first 12 items in the array and shuffle them. The array may contain dozens of items, and I want to shuffle through the entire array. What am I doing wrong?
We need to see more code. As of right now according to the code, it should display every result (not just 12). This must mean that you're cutting the array down to 12 before you even shuffle it.
I just wrote this function to shuffle an array. It return the array shuffled so you can still keep the original array:
`function lowellshuffle($unshuff) {
$co = count($unshuff);
$m=0;
for ($i=0;$i<$co;$i++){
$p = rand(0,count($unshuff)-1);
$shuffled[$i] = $unshuff[$p];
for ($j=0;$j<count($unshuff);$j++){
if ($unshuff[$j] !== $shuffled[$i]){
$nq[$j- $m] = $unshuff[$j];
}
else {$m++;}
}
unset($unshuff);
$unshuff = $nq;
unset($nq);
$m=0;
}
return $shuffled;
}`
I have been trying to get this to work for a while now!
What I am trying to do is sort two arrays, so they both get ordered depending on the values inside one of the arrays. I don't know how to "attach" the arrays so both get ordered.
Here is my code:
$html = file_get_html('http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=hat&x=0&y=0');
$test = strtolower("Beechfield Turn-up Beanie");
$arrayT = array();
$arrayP = array();
foreach ($html->find('div.product') as $results) {
foreach ($results->find('a.title') as $title) {
$titleLow = strtolower($title->plaintext);
similar_text($test, $titleLow, $percent);
$arrayT[] = $title->plaintext;
$arrayP[] = round($percent);
}
}
I am comparing how similar the titles brought back from the outside website are to the variable $test, which in this case is just an example.
Next I want my output to be sorted depending on the $percent variables. For example with no sorting the output would be:
title-1 55
title-2 90
title-3 66
However I want it to be sorted:
title-2 90
title-3 66
title-1 55
I have tried using array_multisort however it would only sort each array independently. I have had a look at usort and ksort as well but couldn't get a working answer.
Any help would be appreciated! I have never used any kind of sorting in PHP and have only started learning arrays so please go easy on me.
I would suggest you to do this:
Instead of storing title and percentage in two different array.
you can have array indices as the titles.
Like this:
$html = file_get_html('http://www.amazon.co.uk/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=hat&x=0&y=0');
$test = strtolower("Beechfield Turn-up Beanie");
$arrayTP = array();
foreach ($html->find('div.product') as $results) {
foreach ($results->find('a.title') as $title) {
$titleLow = strtolower($title->plaintext);
similar_text($one, $titleLow, $percent);
$arrayTP[$title->plaintext] = round($percent);
}
}
You can sort it later using an array sort function based on the percentage. Use this: asort.
Because:
This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.
For printing do this:
foreach($arrayTP as $title => $percent ) {
.
.
.