簡體   English   中英

如何從數組數組(多維數組)加入逗號分隔的字符串?

[英]How to join into a comma-separated string from array of arrays (multidimensional-array)?

好的,我知道要從PHP的字符串數組中獲取逗號分隔的字符串,您可以執行

$stringA = array("cat","dog","mouse");
$commaSeperatedS = join(',', $stringA);

但是,如果我有一個數組數組(而不是簡單的字符串數組)怎么辦?

$myAssociativeA = 
      array(
           [0] => array("type"=>"cat", "sex"=>"male")
           , [1] => array("type"=>"dog", "sex"=>"male")
      );

我的目標是從每個數組的特定屬性(例如“ type”)中獲取一個逗號分隔的字符串? 我試過了

$myGoal = join(',', $myAssociativeA{'type'});

在這種情況下,我對$myGoal目標值為"cat,dog" 有沒有一種簡單的方法而不必手動遍歷每個數組,提取屬性然后在最后進行聯接?

這應該為您工作:

(這里我只是用array_column()得到想要的列,然后用implode()其內array_column()

echo implode(",", array_column($myAssociativeA, "type"));

另一個選擇是使用array_walk()返回所需的密鑰:

array_walk($myAssociativeA, function(&$value, $key, $return) {
  $value = $value[$return];
}, 'type');

echo implode(', ', $myAssociativeA); // cat, dog

對於較舊的PHP版本有用-@ Rizier123使用array_column()的答案非常適合PHP 5.5.0+

如果您的PHP <5.5.0和> = 5.3.0(感謝@ Rizier123 )並且不能使用array_column()可以使用array_column()

<?php

$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));

$myGoal = implode(',', array_map(function($n) {return $n['type'];}, $myAssociativeA));

echo $myGoal;
?>

編輯: @scrowler的注釋中的建議,現在的代碼是:

<?php

$myAssociativeA = array(array("type"=>"cat", "sex"=>"male"), array("type"=>"dog", "sex"=>"male"));
$column = 'type';

$myGoal = implode(',', array_map(function($n) use ($column) {return $n[$column];}, $myAssociativeA));

echo $myGoal;
?>

輸出:

貓狗

在以下網址中了解有關array_map更多信息: http : array_map

您只需要遍歷數組並自己生成字符串。

<?php
   $prepend = '';
   $out = '';
   $myAssociativeA = array(
      array('type' => 'cat'),
      array('type' => 'dog')
   );

   foreach($myAssociativeA as $item) {
      $out .= $prepend.$item['type'];
      $prepend = ', ';
   }
   echo $out;
?>

您可以輕松地將其轉換為函數。

<?php
   function implode_child($array,$key) {
     $prepend = '';
     $out = '';
     foreach($array as $item) {
        $out .= $prepend.$item[$key];
        $prepend = ', ';
     }
     return $out;
   }
?>

好的,假設您的assoc數組字段的排序方式始終與您可以像這樣使用代碼段相同。 但是,您仍然需要遍歷數組。

$csvString = "";
foreach ( $myAssociativeA as $row ) {
    $csvRow = implode(",", $row);
    $csvString .= $csvRow . PHP_EOL;
}

現在,如果您不想將整個CSV存儲在變量中(您不應該這樣做),請查看http://www.w3schools.com/php/func_filesystem_fputcsv.asp並查看示例如何將其直接放入文件。

暫無
暫無

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

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