Php 将数组中的数据合并到一个变量中

Php 将数组中的数据合并到一个变量中,php,mysql,Php,Mysql,我试图将数组中的几个结果合并到一个变量中 $sqlNameForCode = "Select dim_InvoiceRef from dimensions"." Where dim_FileRef = '".$addRow[$FieldName]."'"; $qryNameForCode = mysql_Query($sqlNameForCode); While($arrNameForCode = mysql_fetch_array($qryNameForCode)) { $addRow

我试图将数组中的几个结果合并到一个变量中

$sqlNameForCode = "Select dim_InvoiceRef from dimensions"." Where dim_FileRef = '".$addRow[$FieldName]."'";
$qryNameForCode = mysql_Query($sqlNameForCode);
While($arrNameForCode = mysql_fetch_array($qryNameForCode)) {
    $addRow[$FieldName] = $arrNameForCode['dim_InvoiceRef'];
}
我需要变量
$addRow[$FieldName]
来包含从数组中获取的所有字段。但是,因为它在While循环中,所以变量中只剩下最后一个字段

$sqlNameForCode = "Select dim_InvoiceRef from dimensions"." Where dim_FileRef = '".$addRow[$FieldName]."'";
$qryNameForCode = mysql_Query($sqlNameForCode);
While($arrNameForCode = mysql_fetch_array($qryNameForCode)) {
    $addRow[$FieldName] = $arrNameForCode['dim_InvoiceRef'];
}
例如,查询提取以下结果

Apple
Banana
Orange
我需要
echo$addRow[$FieldName]
来显示
苹果香蕉橙
,此时它正好等于


任何帮助都很好,谢谢

你需要把它做成一个数组

While($arrNameForCode = mysql_fetch_array($qryNameForCode)) {
    $addRow[$FieldName][] = $arrNameForCode['dim_InvoiceRef']; //notice the extra braces
}

echo implode(' ', $addRow[$FieldName]); //prints the values in the array separated by a space
或者直接将其分配给字符串

$addRow[$FieldName] = "";//defaults
While($arrNameForCode = mysql_fetch_array($qryNameForCode)) {
    $addRow[$FieldName] .= $arrNameForCode['dim_InvoiceRef']; //string concatenation
}
echo $addRow[$FieldName];

你需要把它做成一个数组

While($arrNameForCode = mysql_fetch_array($qryNameForCode)) {
    $addRow[$FieldName][] = $arrNameForCode['dim_InvoiceRef']; //notice the extra braces
}

echo implode(' ', $addRow[$FieldName]); //prints the values in the array separated by a space
或者直接将其分配给字符串

$addRow[$FieldName] = "";//defaults
While($arrNameForCode = mysql_fetch_array($qryNameForCode)) {
    $addRow[$FieldName] .= $arrNameForCode['dim_InvoiceRef']; //string concatenation
}
echo $addRow[$FieldName];

下面是一个基于MySQL的解决方案,您可能会发现它更简单:

$sql = "SELECT GROUP_CONCAT(dim_InvoiceRef SEPARATOR ' ') FROM dimensions WHERE dim_FileRef = '".$field."'";

$query = mysql_query($sql);
$result = mysql_fetch_row($query);

echo $result[0]; // Should show 'Apple Orange Banana' etc.

我冒昧地重命名了示例中的一些变量,以使其更易于理解。除非以后在程序中需要使用相同的数据执行不同的操作,否则这应该是可行的

下面是一个基于MySQL的解决方案,您可能会发现它更简单:

$sql = "SELECT GROUP_CONCAT(dim_InvoiceRef SEPARATOR ' ') FROM dimensions WHERE dim_FileRef = '".$field."'";

$query = mysql_query($sql);
$result = mysql_fetch_row($query);

echo $result[0]; // Should show 'Apple Orange Banana' etc.
我冒昧地重命名了示例中的一些变量,以使其更易于理解。除非以后在程序中需要使用相同的数据执行不同的操作,否则这应该是可行的