我的php中有多个函数,看起来像这样
function linkExtractor($html){
$doc = new DOMDocument();
$last = libxml_use_internal_errors(TRUE);
$doc->loadHTML($html);
libxml_use_internal_errors($last);
$xp = new DOMXPath($doc);
$result = array();
foreach ($xp->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' infaa ')]") as $node)
$result[] = trim($node->textContent);
return $result;
}
我正在使用它将它们变成json:
echo json_encode(array("info" => linkExtractor($html),
"dates" => linkExtractor2($html),
"names" => linkExtractor3($html),
"images" => linkExtractor4($html),
"genres" => linkExtractor5($html)
));
但这会像这样返回json:
{
"name":["melter",...],
"date":["05/24/14",...],
"image":["pictu.jpg",...],
"genre":["art",...],
"info":["Lorem ipsum",...]
}
我希望对它们进行批处理,以便将每个结果的第一个放入如下的大括号中:
[
{
"name": "melter",
"date": "05/24/14",
"image": "pictu.jpg",
"genre": "art",
"info": "Lorem ipsum"
},
...
]
我该怎么做?
<table width="703" border="0" align="center">
<tr>
<th width="697" scope="col">
<div id='gopro-hero-3'>
<a href="Bits&Bobs/gopro-hero-3.html"><img src="pictu.jpg" alt="" width="700" height="525" class="images gopro-hero-31" /></a>
</div>
</th>
</tr>
<tr>
<td valign="top" class="type" align="centre">
<table width="100%" border="0" align="right">
<tr>
<th width="48%" class="type genre" scope="col">art</th>
<th width="3%" class="" scope="col"> </th>
<th width="49%" class="date" scope="col">05/24/14</th>
</tr>
</table>
</td>
</tr>
<tr>
<td align="left">
<table width="100%" border="0">
<tr>
<th class="name" align="left" scope="col"><a class="gopro-hero-31" href="Bits&Bobs/gopro-hero-3.html">melter</a>
</th>
</tr>
<tr>
<th class="infaa" align="left" scope="col">Lorem ipsum</th>
</tr>
</table>
答案 0 :(得分:1)
我想linkextractor函数返回的数组长度相同。
$arr = array();
$info = linkExtractor($html);
$dates = linkExtractor2($html);
$names = linkExtractor3($html);
$images = linkExtractor4($html);
$genres = linkExtractor5($html);
for ($i=0; $i<count($info); $i++) {
$arr[] = array("info" => $info[$i], "date" => $dates[$i], "name" => $names[$i], "image" => $images[$i], "genre" => $genres[$i]);
}
echo json_encode($arr);
答案 1 :(得分:0)
假设每个数组具有相同数量的元素并假设您以相同的顺序提取它们,您可以像这样循环:
$count = count($names);
$result = array();
for ($i=0; $i<$countà; ++$i) {
$item = new stdClass;
$item->name = $names[$i];
$item->date = $dates[$i];
// ...
$result[] = $item;
}
echo json_encode($result);
但是,您所做的工作非常低效,您应该重新考虑解析策略,以便一次性提取所有信息。