Pooja Krishna Pooja Krishna - 4 months ago 10
JSON Question

Json results sorting not working in php

Sorting not working..

my controller page

$price = $_POST['price'];

$search = $_POST['search'];
$cat_id = $_POST['category'];

$post1 = file_get_contents("...?search=".$search."&category=".$cat_id);
$products = CJSON::decode($post1, true);
if($price == 1)
{
function prod($a, $b) {
return $a["retail_price"] - $b["retail_price"];
}

usort($products, "prod");

echo "<pre>";print_r($products);die;
}


it does not print the result in a sorted order..
$products is an array

Array
(
[0] => Array
(
[0] => Array
(
[id] => 11027
[title] => SPIDERMAN ENGRAVED LIGHTER
[barcode] => LEN-0022
[qty] => 8
[url] => http://www.ebay.com/itm/-/381279328138?
[retail_price] => 9.99
[category] => Array
(
[id] => 34
[name] => ENGRAVED LIGHTERS
)

[bin] => Array
(
[id] => 346
[name] => F10
)

[images] => Array
(
[0] => Array
(
[small] => http://www.heygidday.biz/portal//timthumb.php?src=/files/products/dscn124900.jpg&w=30
[middle] => http://www.heygidday.biz/portal//timthumb.php?src=/files/products/dscn124900.jpg&w=100
[source] => http://www.heygidday.biz/portal/files/products/dscn124900.jpg
)

)

)

[1] => Array
(
[id] => 11548
[title] => SPIDER MAN Black Lighter
[barcode] => LEN-0067
[qty] => 6
[url] => http://www.ebay.com/itm/-/361369988738?
[retail_price] => 10.99
[category] => Array
(
[id] => 34
[name] => ENGRAVED LIGHTERS
)

[bin] => Array
(
[id] => 346
[name] => F10
)

[images] => Array
(
[0] => Array
(
[small] => http://www.heygidday.biz/portal//timthumb.php?src=/files/products/len-00670.jpg&w=30
[middle] => http://www.heygidday.biz/portal//timthumb.php?src=/files/products/len-00670.jpg&w=100
[source] => http://www.heygidday.biz/portal/files/products/len-00670.jpg
)
)
)
)
)


This is the result i get when array is sorted by the retail_price.Sorting does not work ,why is it so???? Can anyone help me with this????
Waiting for the response...........

Answer

$products is not just an array, but it's an array in an array:

$products = array( array( product1, product2 ) );

You don't want that surrounding array, so just do

    $post1 = file_get_contents("...?search=".$search."&category=".$cat_id);
    $data = CJSON::decode($post1, true);
    $products = $data[0];

    //...

Site note: You shouldn't declare a function within the running code. This tends to result in strange errors.

Instead just declare it in the top, or use an anonymous function.

$prod = function($a, $b) {
    return $a["retail_price"] - $b["retail_price"];
}

usort($products, $prod);