douyi8315 2017-02-10 12:32
浏览 35

从数组中获取数据的问题

Whenever I seek to show the contents of an array based on data from an SQL database, the output always is prefixed with the word "Array". It doesn't matter whether I use echo, print_r(), var_dump() or otherwise. Code below. Any ideas greatly received!

$prefix1 = ''; 
$tasks = array($product, $service, $order, $social, $competition, $dataOther);
foreach ($tasks as $task) {
    if ($task == '') {
        unset($task);
    } else {
        $tasks .= $prefix1 . '' . $task . '';
        $prefix1 = ', ';
    }
} 
echo $tasks;

Output - "Array" followed by the contents of $tasks

Edit: I cannot use implode(', ', $tasks) because each of the inputs (i.e. $product, $service etc.) could be blank and therefore the outcome would be ",," in places.

Hope that's clearer.

  • 写回答

1条回答 默认 最新

  • dsbtwy1329 2017-02-10 12:36
    关注

    You are overwriting your array in the loop, casting it to a string when you add a string to it. You should use a different name for the string you are building.

    Although you don't really need a loop for this, you can replace your code with just:

    $tasks = array($product, $service, $order, $social, $competition, $dataOther);
    echo implode(', ', $tasks);
    

    Edit: Based on your edit - that the variables can be blank - you can filter the empty values before you implode: array_filter without a callback function / second parameter removes empty values:

    $tasks = array($product, $service, $order, $social, $competition, $dataOther);
    echo implode(', ', array_filter($tasks));
    

    Note that this will also filter strings like 0 so if that is not what you want, you would have to add a callback function that meets your requirements.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题