1

我遇到了将数组作为字符串回显的问题,我之前的代码如下所示:

$years = array('2013', '2014');
foreach($years as $year) {
    //do rest of the code

我认为现在是让其余代码更加动态和“放手”的时候了,所以我准备了一个从数据库年份中选择的小函数,而不是在新年到来时手动输入它。

这是年份提取的代码:

function order_count_for_year($us_id) {
$orders_for_year = array();

$query = "SELECT DISTINCT YEAR(`date_posted`) FROM `orders` WHERE `us_id` = {$us_id}";

$query = mysql_query($query);

while($row = mysql_fetch_assoc($query)) {
    $orders_for_year[] = $row;
}

return $orders_for_year;
}

因此,如果我为这个函数执行 foreach,它会正确返回 2013 和 2014,但我不能这样,所以我这样做了:

echo implode(', ', order_count_for_year($us_id));

它不起作用,它返回:array, array,我不明白为什么它不起作用,它适用于应用程序中的不同数组,但不适用于这个......

最后我想出了这样的废话:

$some_variable = '';
foreach(order_count_for_year($us_id) as $test) { $some_variable .= $test['YEAR(`date_posted`)'] . ', '; }
echo $some_variable;

It works, but i didnt want to make it that complicated, i dont feel that this is good idea. Anybody has idea why isnt it working with implode, or how to make it work without loop?

Please dont post with answers that i have to use variables for implode, its not needed and even if - i tested it, doesnt work.

4

2 回答 2

3

That's because you are adding $row to the array each time, which is itself an array.

You might be interested in mysql_fetch_row:

while($row = mysql_fetch_row($query)) $orders_for_year[] = $row[0];

With this, it doesn't matter what the column is called.

Alternatively, use an alias:

mysql_query("SELECT DISTINCT YEAR(`date_posted`) AS `year` FROM ...

Then you can access it as $row['year'] in your associative array.

Also, have a +1 for actually using backticks around your column names.

于 2013-09-13T20:14:59.997 回答
1

If you don't know what the data looks like you are dealing with, there is a simple method: Use var_dump($variable).

If used, you'd immediately spot that you don't have an array with two year-strings inside, but two layers of arrays.

于 2013-09-13T20:17:33.010 回答