【问题标题】:Separate arrays with foreach with comma, but when it comes to the last string, delete the comma [duplicate]用逗号分隔数组,但是当涉及到最后一个字符串时,删除逗号[重复]
【发布时间】:2021-12-09 11:20:13
【问题描述】:

我将我的数据列为数组,但看起来我需要一些帮助,用逗号分隔它。

按照我的代码:Php

foreach($product as $value){
echo $value->sku.'|'.$value->productID'|'.$value->name', ';
}
/* This Output         : 12.062|221|Shoes, 02.123|101|T-shirt, */

/* The Output i wanted : 12.062|221|Shoes, 02.123|101|T-shirt  */

如何删除数组中最后一个返回元素的逗号?

谢谢你。

【问题讨论】:

    标签: php


    【解决方案1】:

    有多种方法可以做到这一点。

    您可以使用rtrim 删除字符串中的最后一个字符

    $string = rtrim($string, ", ");
    

    你可以只substr最后一个字符

    $string = substr($string, 0, -1);
    

    甚至在您的foreach loop 中,因为您正在其中进行回显,您可以验证它是否是您所在数组的最后一项,而不是添加最后一个,

    $lastkey = end($product);
    foreach($product as $key => $value){
        echo $value->sku.'|'.$value->productID'|'.$value->name . ($key != $lastkey ? ', ' : '');
    }
    

    【讨论】:

    • 谢谢你:))))
    猜你喜欢
    • 2019-02-12
    • 2014-09-14
    • 2014-02-11
    • 2011-10-05
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多