1

我在 foreach 循环期间创建了一个数组数组(我认为):

$collectGroup = array();
foreach ($topTenList->searchResult->item as $group) {
    $collectGroup['title'] = $group->title;
    $collectGroup['price'] = $group->sellingStatus->convertedCurrentPrice;
    $collectGroup['image'] = $group->galleryURL;
    $collectGroup['url']   = $group->viewItemURL;
}

var 转储数组输出:

array(4) {
  ["title"]=>
  object(SimpleXMLElement)#13 (1) {
    [0]=>
    string(74) "title 1"
  }
  ["price"]=>
  object(SimpleXMLElement)#16 (2) {
    ["@attributes"]=>
    array(1) {
      ["currencyId"]=>
      string(3) "GBP"
    }
    [0]=>
    string(9) "1500000.0"
  }
  ["image"]=>
  object(SimpleXMLElement)#14 (1) {
    [0]=>
    string(63) "http://www.website.com/image1.jpg"
  }
  ["url"]=>
  object(SimpleXMLElement)#15 (1) {
    [0]=>
    string(140) "http://www.website.com"
  }
}

array(4) {
  ["title"]=>
  object(SimpleXMLElement)#11 (1) {
    [0]=>
    string(80) "title 2"
  }
  ["price"]=>
  object(SimpleXMLElement)#12 (2) {
    ["@attributes"]=>
    array(1) {
      ["currencyId"]=>
      string(3) "GBP"
    }
    [0]=>
    string(9) "8000088.0"
  }
  ["image"]=>
  object(SimpleXMLElement)#17 (1) {
    [0]=>
    string(63) "http://www.website.com/image2.jpg"
  }
  ["url"]=>
  object(SimpleXMLElement)#16 (1) {
    [0]=>
    string(140) "http://www.website.com"
  }
}

我现在想做的是按价格降序对数组中的数组进行排序。所以在这种情况下,它应该具有价格为 8000088.0 的数组高于价格为 1500000.0 的数组。我努力了:

ksort($collectGroup['price'], SORT_NUMERIC);

但没有运气,请帮助

4

2 回答 2

2
usort($collectGroup, function ($first, $second) {
  return $second['price'] - $first['price'];
});

阅读有关 usort 的文档,您将了解它是如何工作的。

于 2013-05-17T08:25:58.283 回答
0

实际上,据我所知,您创建了一个SimpleXMLElement对象数组,而不是多维数组。要获得多维数组,您应该执行以下操作:

        $collectGroup = array();
        foreach ($topTenList->searchResult->item as $group) {
            $collectGroup['title'] = $group->title[0];
            $collectGroup['price'] = $group->sellingStatus->convertedCurrentPrice[0];
            $collectGroup['image'] = $group->galleryURL[0];
            $collectGroup['url']   = $group->viewItemURL[0];
        }

你有一个多维数组。抱歉,如果我对 中的数组访问有误SimpleXMLElement,但不经常使用它,我更喜欢 JSON。无论如何@aaaaaa123456789(好名字:))向您展示了一个好方法。

于 2013-05-17T08:33:09.390 回答