循环遍历数组以查找某个单词然后打印包含该单词的所有对象

时间:2014-02-20 19:59:42

标签: php arrays json

我不确定我所问的是否合理,但我会尽力解释。我有一些JSON数据,我使用cURL打印出来,对象的一部分打印出来,

国内啤酒(0.5升吃水),餐厅

然后下一行将是

新鲜白面包(500克),市场

我想知道是否有可能遍历数据数组并查看哪些部分包含“餐馆”一词并将它们组合成一个变量,然后对makets执行相同操作?

到目前为止,这是我的数组代码

            $json = json_decode($r);
            $json->monthLastUpdate;
            // search through data for printing
             echo "<div id='results'>";
            echo "<h2> Prices for $country </h2>";

            foreach($json->prices as $prices) {
                // echos out the selected items into a list
            echo "</div>";


            echo "<p>"  . $prices->item_name . " <br><b> Average price </b>";
                    $pricedata ="$prices->average_price";

               //rounds the numbers down to readable format

            echo number_format((float)$pricedata, 2, '.', '');
            echo  "&#40;";
            echo $currency;
            echo "&#41;";

这是我从查询

收到的JSON数据
    {
       "monthLastUpdate": 3,
      "contributors": 4424,
     "name": "India",
     "prices": [
           {
             "average_price": 0.984819890047,
                "item_name": "Meal, Inexpensive Restaurant, Restaurants",
             "highest_price": 1.96963978009,
               "item_id": 1,
              "lowest_price": 0.64013292853
          },
          {
               "average_price": 4.92409945023,
               "item_name": "Meal for 2, Mid-range Restaurant, Three-course, Restaurants",
                "highest_price": 7.87855912037,
               "item_id": 2,
                "lowest_price": 3.0005
           },

1 个答案:

答案 0 :(得分:0)

如果格式是一致的并且假设项目名称中没有逗号,则可以执行以下操作:

$itemCatalog = array();

foreach($items as $item){
    $chunks = explode("," $item);
    $category = $chunks[1];
    $itemName = $chunks[0];

    $itemCatalog[$category][] = $itemName;
}

之后,您将拥有一个多维数组,其中包含按类别排序的项目。