Reputation: 4245
I have multiple functions inside my php that look like this
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;
}
And I am using this to turn them into json:
echo json_encode(array("info" => linkExtractor($html),
"dates" => linkExtractor2($html),
"names" => linkExtractor3($html),
"images" => linkExtractor4($html),
"genres" => linkExtractor5($html)
));
But this is returning the json like this:
{
"name":["melter",...],
"date":["05/24/14",...],
"image":["pictu.jpg",...],
"genre":["art",...],
"info":["Lorem ipsum",...]
}
I am looking to batch them so the first of each result is put into a curly brackets like this:
[
{
"name": "melter",
"date": "05/24/14",
"image": "pictu.jpg",
"genre": "art",
"info": "Lorem ipsum"
},
...
]
How can I do this?
<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>
Upvotes: 0
Views: 79
Reputation: 3183
I guess the arrays returned by the linkextractor functions are the same length.
$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);
Upvotes: 1
Reputation: 28541
Assuming each array has the same number of elements and assuming you extract them in the same order, you can loop like that:
$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);
However, what you are doing is highly inefficient and you should rethink your parsing strategy to extract all the information in a single pass.
Upvotes: 0