从PHP函数返回JSON

时间:2016-02-22 11:30:21

标签: php json

我想转换这个应该返回JSON数据的PHP函数。

public List getList(String name)
{
     return this.sessionFactory.getCurrentSession().createQuery("FROM P WHERE c_name LIKE ")
        .setString(0,  "%" + name + "%").list();
}

显示如下json文件:

<?php
$query = 'SELECT * FROM `' . mix_player::table() . '` a';
if (isset($_GET['cat']) || isset($_GET['order'])) 
    if (isset($_GET['cat'])) {
        $query .= ' INNER JOIN `' . mix_player::table_cat_rel() . '` b '
            . "ON (a.`id` = b.`idtrack`) WHERE `idcat` = '" . $wpdb->escape($_GET['cat']) . "'";

        $random = $wpdb->get_var('SELECT `random`, `order` FROM `' . mix_player::table_categories() . "` WHERE `id` = '"
            . $wpdb->escape($_GET['cat']) . "'");

        if (!$random)
            $order = $wpdb->get_var(NULL, 1);
    }

    if (isset($_GET['order']))
        $order = $_GET['order'];

    if ($order != '') {
        if (isset($_GET['cat']))
            $query .= ' AND ';
        else
            $query .= ' WHERE ';

        $tracks = mix_player::order_list($query, $order);
    }

} else {
    $random = '0';
}

$query .= ' ORDER BY `id` ASC';

if (isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A))) {
    // option "shuffle = true" not always working into mix. Do it our own way...
    if ($random == 1) { // shuffle tracks?
        list($usec, $sec) = explode(' ', microtime());
        mt_srand((float) $sec + ((float) $usec * 100000));
        $nrows = count($tracks);
        for ($i = 0; $i < $nrows; $i++) {
            $j = mt_rand(0, $nrows - 1);  // pick j at random
            $row = $tracks[$i]; // swap i, j
            $tracks[$i] = $tracks[$j];
            $tracks[$j] = $row;
        }
    }

    foreach ($tracks as $row) {


        $artist = (mix_player::entities($row['artist']));
        echo ($artist);


        $title = (mix_player::entities($row['title']));

        echo ($title);

        $url =(xspf_player::entities($row['url']));
        echo ($url);        

}
}
?>

你能帮助我吗?

提前致谢。

2 个答案:

答案 0 :(得分:2)

您可以简单地创建一个数组并使用所需的值填充它,然后将其作为JSON返回:

function tracks2json( $tracks )
{
    $retval = array();
    foreach( $tracks as $row )
    {
        $array = array();
        $array['artist'] = mix_player::entities($row['artist']);
        $array['title']  = mix_player::entities($row['title']);
        $array['media']  = 'url '.xspf_player::entities($row['url']);
        $array['color']  = '#56B0E8';
        $retval[]        = $array;
    }
    return json_encode( $retval );
}

if( isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A)) )
{
    // Your MySQL routine here

    $json = tracks2json( $tracks );

}

答案 1 :(得分:0)

echo json_encode(array("title"=>$title,"artist"=>$artist,"url"=>$url));