[英]Get values from Multidimensional nested array in PHP
嗨,我正在嘗試從此鏈接上的json文件獲取fulltext
值
我只是在數組的頂部,如何從所有數組(甚至是嵌套數組)中獲取所有值
$json_output = json_decode($json, true);
var_dump($json_output);
foreach($json_output['results'] as $item) {
echo '<br/>'. $item['fulltext'];
}
嘗試在PHP中查看spl,它為您提供了有用的迭代器類,包括專門用於復雜數組的迭代器類-http: //php.net/manual/en/class.recursivearrayiterator.php
另一種方法是
1)將您的json轉換為xml(json-> php array-> xml)-您可以使用此遞歸函數:
function to_xml(SimpleXMLElement $object, array $data)
{
foreach ($data as $key => $value)
{
if (is_array($value))
{
$new_object = $object->addChild($key);
to_xml($new_object, $value);
}
else
{
$object->addChild($key, $value);
}
}
}
$xml = new SimpleXMLElement('<rootTag/>');
to_xml($xml, $my_array);
2)使用XPath查詢xml,以獲取所需的數據集合,例如
$titles = $xml->xpath('//@fulltext');
利用XPath,您還可以通過復雜的約束輕松獲取數據,請查看文檔
找到了解決方案
foreach($json_output['results'] AS $result) {
foreach($result['printouts']['Covers topic'] AS $topic) {
echo "<ul><li>".$topic['fulltext']."</li></ul>";
}
echo "<br/>".$result['fulltext'];
}
謝謝你們的幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.