多维数组 PHP 内爆

2022-08-30 18:48:32

就我的数据结构而言,我有一系列通信,每个communications_id本身包含三条信息:id,score和内容。

我想崩溃这个数组,以获得一个逗号分隔的id列表,我该怎么做?


答案 1

PHP 5.5 更新

PHP 5.5 引入了array_column这是一个方便的快捷方式,可以方便地使用整个类别;它在这里也适用。array_map

$ids = array_column($communications, 'id');
$output = implode(',', $ids);

原始答案

您需要从通信数组中创建一个仅 ID 数组。然后内爆将是微不足道的。

提示:该函数array_map

溶液:

假设 PHP 5.3,否则你必须将回调写成字符串。

$ids = array_map(function($item) { return $item['id']; }, $communications);
$output = implode(',', $ids);

答案 2

您可以查看array_walk_recursive功能。这是创建递归数组到字符串转换的工作片段:

$array = 
  array(
    "1"    => "PHP code tester Sandbox Online",  
    "foo"  => "bar", 
     5 , 
     5     => 89009, 
    "case" => "Random Stuff", 
    "test" => 
       array(
         "test"  => "test221",
         "test2" => "testitem"
       ),
    "PHP Version" => phpversion()
  );

$string="";

$callback = 
  function ($value, $key) use (&$string) {
     $string .= $key . " = " . $value . "\n";
  };

array_walk_recursive($array, $callback);

echo $string;
## 1 = PHP code tester Sandbox Online
## foo = bar
## 2 = 5
## 5 = 89009
## case = Random Stuff
## test = test221
## test2 = testitem
## PHP Version = 7.1.3

推荐