dopod0901 2014-05-28 11:25
浏览 30
已采纳

php字典数组

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?


HTML snippet:

<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>
  • 写回答

2条回答 默认 最新

  • duanjue2560 2014-05-28 12:21
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)