结合阵列形成在PHP多维数组 [英] Combine arrays to form multidimensional array in php

查看:110
本文介绍了结合阵列形成在PHP多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一吨的答案,但我似乎无法得到它的权利。我有以下的阵列和我已经试过:

  $ a =阵列(0 =>'1421',1 =>'2241');
$ B =阵列(0 =>'teststring1',1 =>'teststring2');
$ C =阵列(0 =>'teststring3',1 =>'teststring4');
$ D =阵列(0 =>'teststring5',1 =>'teststring6');$ E = array_combine($ A,阵列($ B,$ C,$ d)条);

但有了这个我得到的误差 array_combine()[function.array-结合]:这两个参数应该具有的元素数量相等

我知道这是因为 $ A 的数组值不是关键。这就是为什么我来这里看看,如果我能得到一个答案一定的帮助,可以帮助我使它看起来像这样:

 阵列(2){  [1421] =>阵列([0] => teststring1
                 [1] => teststring3
                 [2] => teststring5
                )  [2241] =>阵列([0] => teststring2
                 [1] => teststring4
                 [2] => teststring6
               )
}


解决方案

如果你有控制创建数组,应创建他们喜欢的:

  $ a =阵列('1421','2241');
$ B =阵列('teststring1','teststring3','teststring5');
$ C =阵列('teststring2','teststring4','teststring6');$ E = array_combine($ A,阵列($ B,$ C));

如果没有,你有遍历它们:

  $结果=阵列();
$值=阵列($ B,$ C,$ D);的foreach($ A $作为指数=> $键){
    $ T =阵列();
    的foreach($值$值){
        $ T [] = $价值[$指数]
    }
    $结果[$关键] = $ T;
}

DEMO

I know there's a ton of answers but I can't seem to get it right. I have the following arrays and what I've tried:

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

But with this I get the error array_combine() [function.array-combine]: Both parameters should have an equal number of elements.

I know it's because the $a's array values aren't keys. That's why I'm coming here to see if I could get some help with an answer that can help me make it look something like this:

array(2) {

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

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


}

解决方案

If you have control over creating the arrays, you should create them like:

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

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

If not, you have to loop over them:

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

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

DEMO

这篇关于结合阵列形成在PHP多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆