如何让函数返回一个json字符串在php中调用它们?

时间:2015-06-17 17:43:12

标签: javascript php json

我制作了以下脚本,但我希望每个脚本只有在调用函数时才会回显json_encode数组。当我尝试定义函数,然后调用它时,它什么都没显示。如果脚本不是在函数中创建的,它就可以工作。如何根据我的用法制作不同的功能然后调用不同的功能?

<?php

ini_set('display_errors', '0');
error_reporting(0);
require_once("include/db.php");
date_default_timezone_set('Asia/Kolkata');

$regno ='14ASDFJ234';
$password = '0';
$name = 'EASPORTS';
$priority = 0;

//fetch priority
$query = "SELECT priority FROM users WHERE regno='{$regno}' AND pass='{$password}' LIMIT 1";
$res = mysql_query($query, $conn) or die(mysql_error());
$found = mysql_fetch_array($res);

if($found)
{
    $priority=$found['priority'];               
}

//echo $priority;
echo 'news feed : <br> '
$sql = "SELECT  * FROM newsfeed";
$result = mysql_query($sql,$conn) or die(mysql_error());

while ($row = mysql_fetch_array($result)) {

    $details[] = array(
        'name' => $row['name'],
        'feed' => $row['feed']         
    );
}   

echo json_encode($details);

// announcement details...
echo "<br> Announcement details: <br>";

$sql1 = "SELECT  * FROM announcements WHERE name = '$name'";
$result1 = mysql_query($sql1,$conn) or die(mysql_error());

while ($row1 = mysql_fetch_array($result1)) {

    $details1[] = array(
        'name' => $row1['name'],
        'pname' => $row1['pname'],
        'date' => $row1['date'],
        'time' => $row1['time'],
        'status' => $row1['status']       
    );
}   

echo json_encode($details1);

//events script...

?>

1 个答案:

答案 0 :(得分:0)

你应该这样做

public function somefunction()
{
        $query = "SELECT priority FROM users WHERE regno='{$regno}' AND pass='{$password}' LIMIT 1";
    $res = mysql_query($query, $conn) or die(mysql_error());
    $found = mysql_fetch_array($res);
    if($found)
    {
            $priority=$found['priority'];


        }

//echo $priority;
echo 'news feed : <br> '
$sql="SELECT  * FROM newsfeed";
$result=mysql_query($sql,$conn) or die(mysql_error());

while ($row=mysql_fetch_array($result)) {



        $details[] = array(
            'name' => $row['name'],
            'feed' => $row['feed']

        );
        }   
        echo json_encode($details);
}

现在当你调用somefunction()时,你会得到json编码的数组