Jump to content

Recommended Posts

I'm having an issue sorting an array.

I'm getting an error of "Warning: ksort() expects parameter 1 to be array, null given in"

 

The print_r output of the array is Array ( [0] => Array ( [text] => 96.1 km [value] => 96113 ) [1] => Array ( [text] => 52.1 km [value] => 52096 ) [2] => Array ( [text] => 102 km [value] => 102064 ) [3] => Array ( [text] => 30.0 km [value] => 29992 ) [4] => Array ( [text] => 43.9 km [value] => 43864 ) [5] => Array ( [text] => 57.4 km [value] => 57408 ) [6] => Array ( [text] => 82.2 km [value] => 82154 ) [7] => Array ( [text] => 73.6 km [value] => 73620 ) [8] => Array ( [text] => 118 km [value] => 118016 ) [9] => Array ( [text] => 137 km [value] => 136921 ) [10] => Array ( [text] => 61.6 km [value] => 61574 ) [11] => Array ( [text] => 74.2 km [value] => 74193 ) [12] => Array ( [text] => 226 km [value] => 226166 ) [13] => Array ( [text] => 140 km [value] => 140145 ) [14] => Array ( [text] => 126 km [value] => 126140 ) [15] => Array ( [text] => 45.5 km [value] => 45520 ) [16] => Array ( [text] => 211 km [value] => 211070 ) [17] => Array ( [text] => 54.1 km [value] => 54145 ) [18] => Array ( [text] => 187 km [value] => 186855 ) [19] => Array ( [text] => 271 km [value] => 271334 ) [20] => Array ( [text] => 219 km [value] => 218848 ) [21] => Array ( [text] => 67.0 km [value] => 67016 ) [22] => Array ( [text] => 13.6 km [value] => 13591 ) [23] => Array ( [text] => 153 km [value] => 153396 ) [24] => Array ( [text] => 11.5 km [value] => 11492 ) ).

 

All I want to do is be able to sort the array by the lowest number in either text or value and display that single number.

<?php

include 'config/db_functions.php';

//run the query
$loop = mysql_query("SELECT * FROM NEW_Venues WHERE game_nights = '5' AND status = '1'")
   or die (mysql_error());



while ($row = mysql_fetch_array($loop))
{

$postcode2 = $row['zip'];
$venue = $row['venue'];
$postcode1=('33071');;


$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode2&destinations=$postcode1&mode=driving&language=en-EN&sensor=false";
 
$data = @file_get_contents($url);
 
$result = json_decode($data, true);

ksort($items);
foreach($result['rows'] as $distance) {;

echo '' . $venue . ' - ' . $distance['elements'][0]['distance']['text'] . ' <br>';


$items[] = $distance['elements'][0]['distance'];
$items1[] = $distance['elements'][0]['distance'];
$itemsname[] = $venue;
}

}




ksort($items1);
foreach ($items1 as $key => $val) {
    echo "$key = $val <br>";
}







print_r(array_values($items));


?>
Link to comment
https://forums.phpfreaks.com/topic/297185-sort-an-array-help/
Share on other sites

I get this when turning those on.

Strict Standards: ksort() [function.ksort]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/Chicago' for 'CDT/-5.0/DST'
Link to comment
https://forums.phpfreaks.com/topic/297185-sort-an-array-help/#findComment-1515612
Share on other sites

Given your array looks like this:

 

$data =  Array (
    0 => Array ( 'text' => '96.1 km', 'value' => 96113 ),
    1 => Array ( 'text' => '52.1 km', 'value' => 52096 ),
    2 => Array ( 'text' => '102 km',  'value' => 102064 ),
    3 => Array ( 'text' => '30.0 km', 'value' => 29992 ),
    4 => Array ( 'text' => '43.9 km', 'value' => 43864 ),
);

 

then using ksort() will merely sort on the keys I highlighted in red. You will need a custom sort, using usort() to sort on the text values

$data =  Array ( 
    0 => Array ( 'text' => '96.1 km', 'value' => 96113 ), 
    1 => Array ( 'text' => '52.1 km', 'value' => 52096 ), 
    2 => Array ( 'text' => '102 km',  'value' => 102064 ), 
    3 => Array ( 'text' => '30.0 km', 'value' => 29992 ), 
    4 => Array ( 'text' => '43.9 km', 'value' => 43864 ),
);

usort($data, function($a, $b) {
        return strnatcmp($a['text'], $b['text']);
        });
        
echo '<pre>',print_r($data, true),'</pre>';

which gives

Array
(
    [0] => Array
        (
            [text] => 30.0 km
            [value] => 29992
        )

    [1] => Array
        (
            [text] => 43.9 km
            [value] => 43864
        )

    [2] => Array
        (
            [text] => 52.1 km
            [value] => 52096
        )

    [3] => Array
        (
            [text] => 96.1 km
            [value] => 96113
        )

    [4] => Array
        (
            [text] => 102 km
            [value] => 102064
        )

)

Alternatively, you can sort on the "value" values using

usort($data, function($a, $b) {
        return $a['value'] - $b['value']);
        });
Edited by Barand
Link to comment
https://forums.phpfreaks.com/topic/297185-sort-an-array-help/#findComment-1515617
Share on other sites

The code provided by Barand should be fine. Im guessing you are running a version of PHP which is older than PHP5.3 (this was released over 6 years ago!). You should consider updating PHP to a much newer version (ideally 5.4.x minimum or preferably php5.6.x)

 

Anyway the alternative to Barands code would be not to use anonymous functions

function sortValues($a, $b) {
    return strnatcmp($a['text'], $b['text']);
}
usort($data, 'sortValues');
Link to comment
https://forums.phpfreaks.com/topic/297185-sort-an-array-help/#findComment-1515631
Share on other sites

Thank you everyone for your help!! I have my code working just as I want on my test hosting server that is running php version 5.2.17. When I move it over to the actual server I want to use it on that is running php version 5.3.29. its not displaying any type of input inside the foreach loop including a simple echo test text.

 

Section of code the issue is in I think

$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode2&destinations=$postcode1&mode=driving&language=en-EN&sensor=false";
 
$data = @file_get_contents($url);
 
$result = json_decode($data, true);



foreach($result['rows'] as $distance) {;

$items2[] = array(
    'info' => $distance['elements'][0]['distance'],
    'venue' => $venue,
    'vid' => $vid,
  );


}

FULL CODE

<?php


ini_set('display_errors', 1);
error_reporting(-1);


include 'config/db_functions.php';




//run the query
$loop = mysql_query("SELECT * FROM NEW_Venues WHERE game_nights = '5' AND status = '1'")
   or die (mysql_error());


$items = null;
$items1 = null;
while ($row = mysql_fetch_array($loop))
{

$postcode2 = $row['zip'];
$venue = $row['venue'];
$vid = $row['vid'];
$postcode1=('33462');;


$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode2&destinations=$postcode1&mode=driving&language=en-EN&sensor=false";
 
$data = @file_get_contents($url);
 
$result = json_decode($data, true);



foreach($result['rows'] as $distance) {;

$items2[] = array(
    'info' => $distance['elements'][0]['distance'],
    'venue' => $venue,
    'vid' => $vid,
  );


}

}




function sortValues($a, $b) {
    return strnatcmp($a['info']['text'], $b['info']['text']);
}
usort($items2, 'sortValues');



$venueid = $items2[0]['vid'];
$venuename = $items2[0]['venue'];

echo "Sunday - $venuename<br>";



?>
Link to comment
https://forums.phpfreaks.com/topic/297185-sort-an-array-help/#findComment-1515712
Share on other sites

Okay I have been playing with this all day and decided to go back to the first script i started with and it's still producing the error.

 

Warning: Invalid argument supplied for foreach() in

<?php
ini_set('display_errors', 1);
error_reporting(-1);


$postcode1=('CB13HR');
$postcode2=('CB23JX');
 
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=$postcode2&destinations=$postcode1&mode=driving&language=en-

EN&sensor=false";
 
$data = @file_get_contents($url);
 
$result = json_decode($data, true);
 
foreach($result['rows'] as $distance) {
	echo 'Distance from you: ' . $distance['elements'][0]['distance']['text'] . ' (' . $distance['elements'][0]['duration']['text'] . 

' in current traffic)';
}

?>

 I also tried to replace json_decode with

json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string);, true );

and it returned nothing. Thanks for any and all help ahead of time.

Link to comment
https://forums.phpfreaks.com/topic/297185-sort-an-array-help/#findComment-1515726
Share on other sites

further to my reply above, if your previous code did have a $result['rows'] in the json decoded data, but it doesn't now, your file_get_contents() is likely failing. you should never use the @ error suppressor in any code.

 

do you get any php errors from the code after you remove the @ in front of the file_get_contents() statement?

Edited by mac_gyver
Link to comment
https://forums.phpfreaks.com/topic/297185-sort-an-array-help/#findComment-1515731
Share on other sites

First off let me thank everyone for their help so far. After trying a few different things and getting an error message. I figured out that allow_url_fopen is OFF. How would I go about CURL to get the data I'm requesting since I'm pretty sure that would be an alternative option.

Link to comment
https://forums.phpfreaks.com/topic/297185-sort-an-array-help/#findComment-1515786
Share on other sites

there's a ton of curl examples to be found by searching the web.

 

the following basic example should work for you (provided that the curl extension is enabled) -

$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=CB13HR&destinations=CB23JX&mode=driving&language=en-EN&sensor=false";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = json_decode(curl_exec($ch), true);

echo '<pre>';
print_r($result);
Link to comment
https://forums.phpfreaks.com/topic/297185-sort-an-array-help/#findComment-1515787
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.