在从MySQL选择添加之前,将对象添加到PHP数组

时间:2012-09-23 15:52:08

标签: php arrays json

我有一个PHP页面编码MySQL选择JSON。 我想添加一个“状态值”作为我的数组的第一个对象。

PHP代码

{
//CREATE USER UNKNOWN ARRAY RESULT
$Statusresult = mysql_query("SELECT TEXT_KEY, TEXT_VALUE FROM T_TEXTS WHERE TEXT_KEY = 'USER_FAILED' ") or die(mysql_error());
$Statusrows = array();
while($s = mysql_fetch_assoc($Statusresult)) 
{
    $Statusrows[] = $s;
}
print json_encode($Statusrows);

}

结果是:

{
"TEXT_KEY" = "USER_FAILED";
"TEXT_VALUE" = "UNKNOWN USER";

}

我想添加第一个对象手册,结果如下:

        {
    "STATUS" = "1";
    "TEXT_KEY" = "USER_FAILED";
    "TEXT_VALUE" = "UNKNOWN USER";
}

我该怎么做?

我尝试过这种方法,但不知何故有错误......

{
    //CREATE USER UNKNOWN ARRAY RESULT
    $Statusresult = mysql_query("SELECT TEXT_KEY, TEXT_VALUE FROM T_TEXTS WHERE TEXT_KEY = 'USER_FAILED' ") or die(mysql_error());
    $Statusrows = array();
    $Statusrows = { "STATUS" => "1" };
    while($s = mysql_fetch_assoc($Statusresult)) 
    {
    //  $Statusrows[] = $s;
        array_push($Statusrows, $s);    
    }
    print json_encode($Statusrows);
}

3 个答案:

答案 0 :(得分:4)

在其上添加 虚拟列

SELECT '"1"' AS `STATUS`, TEXT_KEY, TEXT_VALUE 
FROM T_TEXTS 
WHERE TEXT_KEY = 'USER_FAILED'

SQLFiddle Demo

答案 1 :(得分:1)

您可以使用array union operator (+)­Docs

$Statusrows[] = ["STATUS" => "1"] + $s;

或者:

$status1 = ["STATUS" => "1"];
while ($s = mysql_fetch_assoc($Statusresult)) 
{
    $Statusrows[] = $status1 + $s;
}

这将使您无需在SQL中处理该逻辑。

答案 2 :(得分:0)

尝试以下:

$Statusrows = array();
while($s = mysql_fetch_assoc($Statusresult)) 
{
    $s["STATUS"] = "1";
    $Statusrows[] = $s;
}