使用键和值

时间:2016-06-09 18:41:27

标签: php arrays codeigniter multidimensional-array

我有PHP数组,如:

Array
(
[11] => Array
    (
        [0] => foo
        [1] => bar
        [2] => hello
    )

[14] => Array
    (
        [0] => world
        [1] => love
    )

[22] => Array
    (
        [0] => stack
        [1] => overflow
        [2] => yep
        [3] => man
    )
 )

我希望结果为:

array (
 'foo' => '11',
 'bar' => '11',
 'hello' => '11',
 'world' => '14',
 'love' => '14',
 'stack' => '22',
 'overflow' => '22',
 'yep' => '22',
 'man' => '22'
 )

foreach内尝试了foreach,但仍然无法做到这一点。只有两个级别。

2 个答案:

答案 0 :(得分:2)

您没有展示foreach次尝试,但这很简单:

foreach($array as $key => $val) {
    foreach($val as $v) {
        $result[$v] = $key;
    }
}

如果无法保证内部foreach成为数组,则可以将其if(in_array())包裹起来。此外,所有子数组值必须是唯一的,否则您只能得到最后一个的键/值。

这是另一种方式:

$result = array();

foreach($array as $key => $val) {
    $result = array_merge($result,
                array_combine($val, array_fill(0, count($val), $key)));
}

使用内部数组的值作为键创建结果数组,并使用父数组键填充值。与之前的结果合并。

答案 1 :(得分:1)

您可以使用FOREACH循环轻松完成此操作,如下所示。顺便说一句,你也可以测试它HERE.

    <?php

        $arr        = [
            "11" =>["foo", "bar", "hello"],
            "14" =>["world", "love"],
            "22" =>["stack", "overflow", "yep", "man"],
        ];

        $arrFinal   = array();
        foreach($arr as $intKey=>$subArray){
            if(is_array($subArray)){
                foreach($subArray as $ikey=>$value){
                    $arrFinal[$value] = $intKey;
                }
            }
        }
        var_dump($arrFinal);

VAR_DUMP的结果

        array (size=9)
          'foo' => int 11
          'bar' => int 11
          'hello' => int 11
          'world' => int 14
          'love' => int 14
          'stack' => int 22
          'overflow' => int 22
          'yep' => int 22
          'man' => int 22