将数据库转换为JSON

马克思主义

我有一种将JSON创建到看起来像这样的数组中的方法:

[{"date":"","name":"","image":"","genre":"","info":"","videocode":""},{...},{...}]

我首先尝试从html页面(而不是数据库)中获取数据,如下所示:

$arr = array();

$info = linkExtractor($html);
$dates = linkExtractor2($html);
$names = linkExtractor3($html);
$images = linkExtractor4($html);
$genres = linkExtractor5($html);
$videocode = linkExtractor6($html);

for ($i=0; $i<count($images); $i++) {
    $arr[] = array("date" => $dates[$i], "name" => $names[$i], "image" => $images[$i], "genre" => $genres[$i], "info" => $info[$i], "videocode" => $videocode[$i]);
}

echo json_encode($arr);

每个地方linkExtractor看起来都像这样-它在一个类中获取所有文本videocode

function linkExtractor6($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), ' '), ' videocode ')]") as $node) 
        $result[] = trim($node->textContent); // Just push the result here, don't assign it to a key (as that's why you're overwriting)

    // Now return the array, rather than extracting keys from it
    return $result; 
}

我现在想用数据库来代替。

所以我试图linkExtractor用这个替换每个-显然是连接:

function linkExtractor6($html){ 
    $genre = mysqli_query($con,"SELECT genre
    FROM entries
    ORDER BY date DESC");

    foreach ($genre as $node) 
            $result[] = $node; 
    return $result; 
} 

但是我得到了错误:

为foreach()提供了无效的参数

蜂蜜

避免冗余并运行一个 SELECT

function create_json_db($con){ 
    $result = mysqli_query($con,"SELECT date, name, image, genre, info, videocode
                                 FROM entries
                                 ORDER BY date DESC");

    $items= array();
    while ($row = mysqli_fetch_assoc($result)) {
       $items[] = $row;
    }

    return $items ; 
} 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章