Welcome Guest, Not a member yet? Register   Sign In
json_decode, strings, and query results

// Example 1: string is surrounded with double quotes, which is what JSON needs
$a = '"Hello world"';
echo('$a JSON decode is: ' . json_decode($a)); // displays: Hello world


// Example 2: string is not surrounded with double quotes; json_decode *should* ignore this
$b = "Hello world";
echo('$b JSON decode is: ' . json_decode($b)); // displays nothing

I need to return the result of a DB query as a JSON string. When I query the model, I get a result similar to Example 2 above (strings are not surrounded with double quotes; the double quotes are just part of PHP's representation to indicate the value is a string). Thus, the string values from my DB query results disappear when when I json_decode them. (Oddly, though, this "disappearing act" does not occur on a fellow developer's local machine.)

What's going on here? How do I effectively convert my query results to JSON string?

There's really not much point in returning a scalar string as JSON code. The whole purpose is to return a JSON object. That's why JSON stands for JavaScript Object Notation. You may ask, what's the point? Well, the point is that you can take an entire associative array in PHP (query results) and pass that whole array (or even a simple php object) as an object represented in JSON format back to your browser. Then you can referrer to any property of that object directly in JavaScript.

I see in your example, you are decoding json. In this case, a scaler string, would not be representative of JSON at all. I'm surprised that having the quotes actually returns the string (but then again, that's probably JSON that I've never tried because what's the point?)

What exactly are you trying to accomplish? If your goal is to return encoded JSON, why are you using the decode function?

Theme © iAndrew 2016 - Forum software by © MyBB