开发者

Json Php / MySql outputting

I have a php page as below:

$sql = "select code as ref, size from product";

$result = mysql_query($sql);

    while($rs=mysql_fetch_assoc($result)){

        $test[] = $rs;
    }

$output['data'][] = $test;

echo json_encode( $output );

This ouputs the following:

{"data":[[{"ref":"ABC","size":"Large"},{"ref":"123","size":"Medium"}]]}

I need to modify the php, so that I can prefix some characters 开发者_StackOverflowbefore the ref value so eg:

ref: ABC should be M-ABC

and

ref: 123 should be M-123

Finally I would also like to add an additional item to the array such as description and this will have a fixed description such as "This product is available in Large" (The value is based on the size).

Thanks


while ($rs = mysql_fetch_assoc($result)) {
    $rs['ref'] = "M-$rs[ref]";
    $rs['description'] = "This product is available in $rs[size]";
    $test[] = $rs;
}


Rather than modify the PHP and have to change your values in a loop, a more unconventional but tidier approach is to modify your SQL and do the string prefixing there:

// Changed to a HEREDOC string for readability
$sql =<<<SQL 
  select CONCAT('M-', code) as ref,
   size,
   CASE
    WHEN (size = 'large') THEN 'this product is available in large'
    WHEN (size = 'small') THEN 'this product is available in small'
    WHEN (size = 'someotherone') THEN 'this product...etc.etc.'
   END AS size_description
  from product;
SQL;

Now this requires no further post-processing in PHP once you've fetched the records. You can hand the array from your fetch loop directly to json_encode()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜