我想用另一个数组键来回显一个数组

时间:2015-11-29 23:49:46

标签: php arrays function

我不知道PHP中是否存在这样的东西..我是初学者,仍然在努力理解

我有两个数组$ num和$ word

$num = array (2, 3, 1, 0);

$word[0]= array("one","two","three","four");
$word[1]= array("ten","twenty","thirty","fourty");
$word[2]= array("one hundred", "two hundred" , "three hundred", "four hundred");
$word[3]= array("one thousand" , "two thousand", "three thousand", "four thousand");

我知道我可以使用echo $word[parent][child];来回显$ word数组中的值 但我想要做的是通过使用$ num数组中的键和值来回显数组$ word

我不知道它是怎么可能的,但我想制作一个函数或任何东西,使它像这样做echo $word[$num"key"][$num"value"]

2 个答案:

答案 0 :(得分:0)

我不确定你是否想要回显所有的num值,但是一个例子可以是循环

foreach($num as $key=>$value){
    echo $word[$key][$value];
}

编辑: 如果你想要特定的键和值,那么就像这样循环$ num

foreach($num as $key=>$value){
    if($key == 'desired_key'){
        $desired_key = $key; 
    }
    if($value == 'desired_value'){
        $desired_value = $value;
    }
    /*
    or put in if both
    if($key == 'desired_key' && $value == 'desired_value'){
        $desired_key = $key; 
        $desired_value = $value;
    }
    */
}
// And after loop just echo desired value
echo $word[$desired_key][$desired_value];

答案 1 :(得分:0)

这将循环$ num并显示$ words。

<?php
$num = [2, 3, 1, 0];
$word = [];
$word[0] = ["one","two","three","four"];
$word[1] = ["ten","twenty","thirty","fourty"];
$word[2] = ["one hundred", "two hundred" , "three hundred", "four hundred"];
$word[3] = ["one thousand" , "two thousand", "three thousand", "four thousand"];

foreach ($num as $i => $n){
    echo $i.' '.$n.' '.$word[$i][$n] . PHP_EOL;
}