index.blade.php中的代码输出为:
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).
)
与[0]和[1]不同,[2]有许多成分。我需要能够将它们全部分开到自己的行(使用逗号和空格等作为断点)。我在JavaScript中实现了这一点:.split(/[:;,.<> /)(]+/);
这里显示的结果将是一个很好的例子: and here is a picture of what it looks like但是在尝试模拟这个时,我得到一个数组到字符串转换错误。
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;
}
答案 0 :(得分:1)
//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 :(得分:1)
我在JavaScript中实现了这一点:
.split(/[:;,.<> /)(]+/);
PHP中的等效代码使用preg_split()
:
$pieces = preg_split('@[:;,.<> /)(]+@', $ingredients[2]);
在PHP中阅读有关PCRE patterns的更多信息。