dongra1984 2013-09-13 20:12
浏览 116
已采纳

Echo数组作为字符串

I've got problem with echo'ing array as a string, the code i had before looks like this:

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

I thought this is time to make the rest of the code more dynamic and "hands-off", so i prepared little function which selects from database years instead of typing it manually when new year is coming.

This is the code for year extract:

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;
}

So if i do foreach for this function it returns 2013 and 2014 corectly but i cant have it that way so i did this:

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

And it doesnt work, it returns: array, array, i dont understand why it doesnt work, it works for different arrays within the apliacation but not with this one ...

finally i came up with bullshit like that:

$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.

  • 写回答

2条回答 默认 最新

  • dongtiao2066 2013-09-13 20:14
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀