我有一个php页面如下:
$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 );
这输出如下:
{"data":[[{"ref":"ABC","size":"Large"},{"ref":"123","size":"Medium"}]]}
我需要修改php,这样我就可以在ref值之前加上一些字符的前缀,例如:
参考:ABC应该是M-ABC
和
ref:123应为M-123
最后,我还想在数组中添加一个额外的项目,例如描述,这将有一个固定的描述,例如“此产品可用于大型”(该值基于大小)。
由于
答案 0 :(得分:0)
while ($rs = mysql_fetch_assoc($result)) {
$rs['ref'] = "M-$rs[ref]";
$rs['description'] = "This product is available in $rs[size]";
$test[] = $rs;
}
答案 1 :(得分:0)
不是修改PHP而是必须在循环中更改您的值,而是更加非常规但更整洁的方法是修改SQL并在那里执行字符串前缀:
// 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;
现在,一旦您获取了记录,就不需要在PHP中进行进一步的后处理。您可以将数组从获取循环直接传递到json_encode()