dpppic5186 2018-02-04 19:30
浏览 47
已采纳

在php中拆分数组的内容

The output of the code inside index.blade.php is this:

Array
(
    [0] => <strong>Wheat</strong> Flour
    [1] => Tomato Purée
    [2] => Mozzarella Cheese (<strong>Milk</strong>) (16%), Pepperoni (10%), Water, Mini Pepperoni (3.5%), Yeast, Dextrose, Rapeseed Oil, Salt, Sugar, Dried Garlic, Dried Herbs, Spice. Pepperoni contains: Pork, Pork Fat, Salt, Dextrose, Spices, Spice Extracts, Antioxidants (Extracts of Rosemary, Sodium Ascorbate), Preservative (Sodium Nitrite). Mini Pepperoni contains: Pork, Pork Fat, Salt, Dextrose, Spices, Spice Extracts, Sugar, Antioxidants (Sodium Erythorbate, Extracts of Rosemary), Preservative (Sodium Nitrite).
)

Unlike [0] and [1], [2] has many ingredients. I need to be able to separate them all out on to their own rows (using commas and spaces etc as break points). I achieved this in JavaScript doing this: .split(/[:;,.<> /)(]+/);

The result shown here would be a good example: split array values when there is a comma however I get an array to string conversion error when attempting to emulate this.

index.blade.php

require_once 'HTTP/Request2.php';

$request = new Http_Request2('https://dev.tescolabs.com/product/');
$url = $request->getUrl();

$headers = array(
    // Request headers
    'Ocp-Apim-Subscription-Key' => 'key',
);

$request->setHeader($headers);

$parameters = array(
    // Request parameters
    'gtin' => '05054402006097',
);

$url->setQueryVariables($parameters);

$request->setMethod(HTTP_Request2::METHOD_GET);

// Request body
$request->setBody("{body}");

try
{
    $response = $request->send();
    $result = $response->getBody();

    //true decodes the json into an associative array instead of stdObject
    $decoded = json_decode($result,true);

    $ingredients = $decoded['products'][0]['ingredients'];
    print_r($ingredients);

}
catch (HttpException $ex)
{
    echo $ex;
}
  • 写回答

2条回答 默认 最新

  • dongzangchui2072 2018-02-04 20:07
    关注
    //true decodes the json into an associative array instead of stdObject
    $decoded = json_decode($result,true);
    
    // can now target ingredient array
    $ingredients = $decoded['products'][0]['ingredients'];
    
    //turn contents into string so can use preg_split(
     $test = implode($ingredients);
    
    $ingredientList = preg_split("/[\s, ]+/", $test);
    print_r($ingredientList);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计