将数组调用到一行变量PHP中

时间:2018-04-11 03:19:09

标签: php mysql arrays

我必须将mysql值(动态)转换为colum name,作为示例

SELECT kdsatker,
MAX(CASE WHEN kdakun=425121 THEN jumlah ELSE NULL END) AS M425121,
MAX(CASE WHEN kdakun=425122 THEN jumlah ELSE NULL END) AS M425122,
MAX(CASE WHEN kdakun=425129 THEN jumlah ELSE NULL END) AS M425129,
MAX(CASE WHEN kdakun=425131 THEN jumlah ELSE NULL END) AS M425131,
MAX(CASE WHEN kdakun=425132 THEN jumlah ELSE NULL END) AS M425132,
MAX(CASE WHEN kdakun=425134 THEN jumlah ELSE NULL END) AS M425134,
MAX(CASE WHEN kdakun=425287 THEN jumlah ELSE NULL END) AS M425287,
MAX(CASE WHEN kdakun=425513 THEN jumlah ELSE NULL END) AS M425513,
MAX(CASE WHEN kdakun=425514 THEN jumlah ELSE NULL END) AS M425514,
MAX(CASE WHEN kdakun=425515 THEN jumlah ELSE NULL END) AS M425515,
MAX(CASE WHEN kdakun=425518 THEN jumlah ELSE NULL END) AS M425518,
MAX(CASE WHEN kdakun=425519 THEN jumlah ELSE NULL END) AS M425519,
MAX(CASE WHEN kdakun=425764 THEN jumlah ELSE NULL END) AS M425764,
MAX(CASE WHEN kdakun=425791 THEN jumlah ELSE NULL END) AS M425791,
MAX(CASE WHEN kdakun=425792 THEN jumlah ELSE NULL END) AS M425792,
MAX(CASE WHEN kdakun=425793 THEN jumlah ELSE NULL END) AS M425793,
MAX(CASE WHEN kdakun=425811 THEN jumlah ELSE NULL END) AS M425811,
MAX(CASE WHEN kdakun=425911 THEN jumlah ELSE NULL END) AS M425911,
MAX(CASE WHEN kdakun=425912 THEN jumlah ELSE NULL END) AS M425912,
MAX(CASE WHEN kdakun=425913 THEN jumlah ELSE NULL END) AS M425913,
MAX(CASE WHEN kdakun=425915 THEN jumlah ELSE NULL END) AS M425915,
MAX(CASE WHEN kdakun=425999 THEN jumlah ELSE NULL END) AS M425999
FROM(SELECT kdsatker,kdakun,sum(jumlah) as jumlah FROM tb_simponi GROUP BY kdsatker,kdakun) as newdata GROUP BY kdsatker

MAX CASE循环基于值数据,我的最后一项工作是基于mysq数据结果创建数组

$sql=array();
while
($baris=mysql_fetch_array($result))
{?>
    <?
    $kodemak=$baris['kdakun'];
    $sql[]="MAX(CASE WHEN kdakun=".$kodemak." THEN jumlah ELSE NULL END) AS M" .$kodemak;
    ?>

<?}

问题是如何调用$ sql变量,该变量包含所有数组循环,逗号分隔为一个$ sql变量

SELECT kdsatker, $sql FROM(SELECT kdsatker,kdakun,sum(jumlah) as jumlah FROM tb_simponi GROUP BY kdsatker,kdakun) as newdata GROUP BY kdsatker

2 个答案:

答案 0 :(得分:0)

如果我没有弄错,你可以使用implode将数组粘合成一个串行字符串。

$sql= implode(",", $sql);

SELECT kdsatker, $sql FROM
(SELECT kdsatker,kdakun,sum(jumlah) as jumlah
 FROM tb_simponi GROUP BY kdsatker,kdakun) as newdata GROUP BY kdsatker

答案 1 :(得分:0)

  

以下是根据您的条件动态调整SQL Query的解决方案:

$sql      = [];
$sql[]    = "SELECT kdsatker";
while($baris = mysql_fetch_array($result)){
    $kodemak = $baris['kdakun'];
    $sql[] = "MAX(CASE WHEN kdakun={$kodemak} THEN jumlah ELSE NULL END) AS M{$kodemak}";
}
$select = " FROM(SELECT kdsatker,kdakun,sum(jumlah) as jumlah FROM tb_simponi GROUP BY kdsatker,kdakun) as newdata GROUP BY kdsatker";
$sql = implode(', ', $sql);
$sql = $sql . $select;

echo $sql;  #Here is your Final Query String