簡體   English   中英

多維數組PHP內爆

[英]Multidimensional Array PHP Implode

就我的數據結構而言,我有一系列通信,每個communications_id本身包含三條信息:id,score和content。

我想破壞這個數組以獲得逗號分隔的id列表,我該怎么做?

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

你可以看看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

來自http://snipplr.com/view.php?codeview&id=10187

class Format {
    static public function arr_to_csv_line($arr) {
        $line = array();
        foreach ($arr as $v) {
            $line[] = is_array($v) ? self::arr_to_csv_line($v) : '"' . str_replace('"', '""', $v) . '"';
        }
        return implode(",", $line);
    }

    static public function arr_to_csv($arr) {
        $lines = array();
        foreach ($arr as $v) {
            $lines[] = self::arr_to_csv_line($v);
        }
        return implode("\n", $lines);
    }

}

對於尋找答案的其他人來說,這就是我能夠做到的:

$singleDimensionalArray = array();

foreach($array["1"]["2"]["3"][...] as $value) {
    $singleDimensionalArray[] = $value;
}

我用這個三維數組。

這個評論基於@jon解決方案,只需添加功能代碼塊

但我必須使用循環,因為array_map不接受第二個參數

function array_column_implode($data_array = array(),$key = 'id', $delimiter = ',')
{
  if (function_exists('array_column'))
  {
    return implode($delimiter, array_column($data_array, $key));
  }
  else
  {
    $new_data_array = array();
    foreach ($data_array as $value) {
      if (isset($value[$key]))
      {
        $new_data_array[] = $value[$key];
      }
    }
    return implode($delimiter, $new_data_array);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM