【问题标题】:concatenate each array into a string将每个数组连接成一个字符串
【发布时间】:2017-05-14 11:43:38
【问题描述】:

所以我有下一个数组:

    Array ( [1] => Array ( [FIRST_NAME] => John [LAST_NAME] => Bon ) 
            [2] => Array ( [FIRST_NAME] => Ray [LAST_NAME] => Bam ) 
          )

我怎样才能得到下一个结果?:

姓名:约翰·邦、雷·巴姆

【问题讨论】:

  • Stack Overflow 不是免费的代码编写服务。您应该尝试自己编写代码。在doing more research 之后,如果您有问题,您可以发布您尝试过的内容,并清楚地解释什么不起作用并提供Minimal, Complete, and Verifiable example。我建议阅读How to Ask 一个好问题。
  • @TomUdding 如果您觉得自己很聪明,您可以提供一些我本可以搜索并记录下来的内容,以实现我的要求。
  • 你应该先搜索一些东西,然后再在 Stack Overflow 上询问它。这可能会对您有所帮助; foreach 循环、内爆、连接。
  • @TomUdding 你看到了吗?现在你很有用。谢谢。
  • 你至少应该为自己付出一点努力。

标签: php arrays


【解决方案1】:

您可以使用foreach() 循环。下面的代码为您提供了内部数组 (0, 1, 2, 3, etc.) 和内部数组本身的索引。然后您可以使用内部数组的键来显示该键的值。

$array = array(
    array("FIRST_NAME" => "Jon", "LAST_NAME" => "Doe"),
    array("FIRST_NAME" => "Jane", "LAST_NAME" => "Doe"),
    array("FIRST_NAME" => "Johnny", "LAST_NAME" => "Doe"),
    array("FIRST_NAME" => "Janie", "LAST_NAME" => "Doe"));

$output = "";

foreach ($array as $i => $values) { // get the inner arrays from the outer array
    if ($i != 0) { // check if it is not the first array
        $output .= ", {$values['FIRST_NAME']} {$values['LAST_NAME']}";
    } else {
        $output .= "{$values['FIRST_NAME']} {$values['LAST_NAME']}";
    }
}

echo $output;
// Jon Doe, Jane Doe, Johnny Doe, Janie Doe

在这段代码中,来自内部数组的值(例如{$values['FIRST_NAME']})被插入到字符串中,您可以查看this answer,了解更多关于为什么要这样做的信息。

有关输出,请参阅 https://3v4l.org/K5s82

【讨论】:

    猜你喜欢
    • 2018-12-18
    • 2013-05-15
    • 2012-02-02
    • 1970-01-01
    • 2022-12-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2017-10-25
    相关资源
    最近更新 更多