如何使用键从两个数组中获取数组值

时间:2016-03-04 12:04:43

标签: php arrays foreach

我的数组是

 $name=>
    Array
        (
            [0] => General
            [1] => General
            [2] => Outdoors
            [3] => Dining
            [4] => Dining
            [5] => Kitchen
            [6] => Kitchen

        )

 $key1=>
   Array
        (
            [0] => 1
            [1] => 2
            [2] => 7
            [3] => 11
            [4] => 12
            [5] => 17
            [6] => 18
        )

数组函数

 foreach ($key1 as $key => $value1) {
                    foreach ($name as $key => $value) {

                        echo $value "=>" $value1 ;
                        //echo "$value1";
                    }
                }

这里我想使用相同的键

打印值

如果$name的索引为[0]且我的$key1也取[0]

即:我的结果应该是

的形式
General => 1
General => 2
Outdoors => 7
Dining => 11
Dining => 12
Kitchen => 17
Kitchen => 18

6 个答案:

答案 0 :(得分:4)

您只需迭代一个数组,而不是两个数组:

foreach ($name as $key => $name_value) {
    echo "$name_value => " . $key1[$key];
}

答案 1 :(得分:1)

您可以使用简单的for循环来执行此操作

for ($i = 0; $i < count($name); $i++) {
    echo $name[$i] . '=>' . $key[$i]
}

答案 2 :(得分:1)

您的代码的问题是您对两个foreach使用相同的变量$key,因此最后一个会覆盖该值。

foreach ($key1 as $key => $value1) {
    foreach ($name as $key => $value) {

        echo $value "=>" $value1 ;
        //echo "$value1";
    }
}

通过组合这两个数组可以使事情变得更容易,使$name数组成为键,$key1数组成为值

$newArray = array_combine($name, $key1);
foreach ($newArray as $name => $key) {
    echo "{$name} =>{$key}";
}

答案 3 :(得分:1)

这对你有用

<?php 
$a1= array('General','Outdoors','Dining ');
$a2= array('1','2','3');
$newArr=array();
foreach($a1 as $key=> $val)
{
    $newArr[$a2[$key]]= $val;
}
echo "<pre>"; print_r($newArr); 
?>

输出

Array
(
    [1] => General
    [2] => Outdoors
    [3] => Dining 
)

答案 4 :(得分:1)

如果您希望输出作为关联数组不允许在关联数组中使用相同的键名,那么这恐怕是不可能的。如果你正在处理关联数组,它总会被覆盖。

虽然你可能有这样的事情:

array_map(function($key, $val) {return array($key=>$val);}, $name, $key1)

输出:

Array ( [0] => Array ( [General] => 1 ) [1] => Array ( [General] => 2 ) [2] => Array ( [Outdoors] => 7 ) [3] => Array ( [Dining] => 11 ) [4] => Array ( [Dining] => 12 ) [5] => Array ( [Kitchen] => 17 ) [6] => Array ( [Kitchen] => 18 ) )

但是如果你想要以字符串格式输出那么可能

for ($i = 0; $i < count($key); $i++) { echo $name[$i] . '=>' . $key[$i].'<br>'; }

答案 5 :(得分:1)

只需更改foreach如下...

foreach ($key1 as $key => $value1) {
                   echo $name[$key] ."=>". $value1."<br>";
            } 
如果您正在通过Linux终端运行,请

<br>替换为\n。另外,请不要错过“.”运算符来连接字符串..

嵌套的foreach不会做你需要的......祝你好运..