簡體   English   中英

在php中組合數組形成多維數組

[英]Combine arrays to form multidimensional array in php

我知道有很多答案,但我似乎無法正確回答。 我有以下數組和我嘗試過的:

$a = array ( 0 => '1421' , 1 => '2241' );
$b = array ( 0 => 'teststring1' , 1 => 'teststring2' );
$c = array ( 0 => 'teststring3' , 1 => 'teststring4' );
$d = array ( 0 => 'teststring5' , 1 => 'teststring6' );

$e = array_combine($a, array($b,$c,$d) );

但是這樣我得到了錯誤array_combine() [function.array-combine]: Both parameters should have an equal number of elements

我知道這是因為$a的數組值不是鍵。 這就是為什么我來這里是為了看看我是否可以得到一些幫助來解決一個可以幫助我使它看起來像這樣的答案:

array(2) {

  [1421]=>array( [0] => teststring1
                 [1] => teststring3
                 [2] => teststring5
                )

  [2241]=>array( [0] => teststring2
                 [1] => teststring4
                 [2] => teststring6
               )


}

如果您可以控制創建數組,您應該像這樣創建它們:

$a = array ('1421' ,'2241');
$b = array ('teststring1', 'teststring3', 'teststring5');
$c = array ('teststring2', 'teststring4', 'teststring6');

$e = array_combine($a, array($b,$c) );

如果沒有,你必須循環它們:

$result = array();
$values = array($b, $c, $d);

foreach($a as $index => $key) {
    $t = array();
    foreach($values as $value) {
        $t[] = $value[$index];
    }
    $result[$key]  = $t;
}

演示

這是功能編碼風格的單行代碼。 使用null函數參數調用array_map()后跟“值”數組將生成所需的子數組結構。 array_combine()進行鍵=> 值關聯。

代碼(演示

var_export(array_combine($a, array_map(null, $b, $c, $d)));

輸出:

array (
  1421 => 
  array (
    0 => 'teststring1',
    1 => 'teststring3',
    2 => 'teststring5',
  ),
  2241 => 
  array (
    0 => 'teststring2',
    1 => 'teststring4',
    2 => 'teststring6',
  ),
)

超級干凈,對吧? 我知道。 當您無法控制初始數組生成步驟時,這是一個有用的小技巧。

這是一個新版本的 array_merge_recursive,它將處理整數鍵。 讓我們知道它是怎么回事。

$a = array ( 0 => '1421' , 1 => '2241' );
$b = array ( 0 => 'teststring1' , 1 => 'teststring2' );
$c = array ( 0 => 'teststring3' , 1 => 'teststring4' );
$d = array ( 0 => 'teststring5' , 1 => 'teststring6' );

$e = array_combine($a, array_merge_recursive2($b, $c, $d));
echo "<pre>";
print_r($e);



function array_merge_recursive2() {
    $args = func_get_args();
    $ret = array();

    foreach ($args as $arr) {
        if(is_array($arr)) {
            foreach ($arr as $key => $val) {
                $ret[$key][] = $val;
            }
        }
    }
    return $ret;
}

暫無
暫無

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

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