-1

I have a PHP page encoding a MySQL select into JSON. I would like to add a "Status value" as the first object of my array.

PHP code

{
//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);

}

This results is:

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

}

I would like to add the first object manual, to have the result look like this:

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

How can I do this ?

I have tried this approach, but somehow there is an error...

{
    //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);
}
1
  • take a look at my answer Commented Sep 23, 2012 at 16:39

3 Answers 3

4

Add a virtual column on it,

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

SQLFiddle Demo

5
  • I tried this, but the result is somehow different...Missing the " around 1 and status Commented Sep 23, 2012 at 16:11
  • Adding a zero element before the SQL would be exact my approach - im just not sure how to do this i tried a few solutions, without any luck... Commented Sep 23, 2012 at 16:18
  • @UlrikVadstrup SELECT '"1"' AS STATUS, ... see my updated answer. Commented Sep 23, 2012 at 16:19
  • hmnn....It looks find when watching it in explorer [{"STATUS":"1","TEXT_KEY":"USER_FAILED","TEXT_VALUE":"UNKNOWN USER"}] but somehowe when decoding in Xcode, the " dissapers around the first object...{ STATUS = 1; "TEXT_KEY" = "USER_FAILED"; "TEXT_VALUE" = "UNKNOWN USER"; } Commented Sep 23, 2012 at 16:29
  • 1
    Problem found - wrong coding in xcode - Thanks a million John Woo :-) Commented Sep 23, 2012 at 16:33
1

You can make use of the array union operator (+)­Docs:

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

Or:

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

This would spare you to deal with that logic inside the SQL.

0

Try below:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.