php foreach循环中的字符串

时间:2018-01-12 14:30:59

标签: php string loops foreach

我的foreach有问题:

解析错误:语法错误,意外的'foreach'(T_FOREACH)

$pdo = new PDO('mysql:host=localhost;dbname=center24', 'root', '');

$sql = "SELECT `Name`, `SP`, `NP`, `PP` FROM `mitarbeiter punkte`";


$string = '{
"cols": [
    {"id":"","label":"Points","pattern":"","type":"string"},
    {"id":"","label":"Start Punkte","pattern":"","type":"number"},
    {"id":"","label":"Negative Punkte","pattern":"","type":"number"},
    {"id":"","label":"Positive Punkte","pattern":"","type":"number"}
  ],
"rows": [
    '.foreach ($pdo->query($sql) as $row) {.'
      {"c":[{"v":"'.$row['Name'];.'","f":null},{"v":'.$row['SP'];.',"f":null},{"v":-'.$row['NP'];.',"f":null},{"v":'.$row['PP'];.',"f":null}]},
    '.}.'  
  ]
}';

echo $string;

1 个答案:

答案 0 :(得分:2)

foreach没有返回循环内生成的输出,所以你需要像这样建立字符串:

$string = '...';
foreach ($pdo->query($sql) as $row) {
    $string .= '...';
}

尽管如此,请不要这样做,而是使用json_encode()