简体   繁体   English

传递逗号分隔的键字符串并根据PHP中的键获取数组的值

[英]Pass comma separated key string and get value of array according to key in PHP

I am trying to get value from array and pass only comma separated key string and get same output without. 我试图从数组中获取值,并且只传递逗号分隔的键串,而没有获得相同的输出。 Is it possible without using foreach statement. 是否可以不使用foreach语句。 Please suggest me. 请给我建议。

<?php
$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");

$keyarray = explode(",",$str);
$valArr = array();
foreach($keyarray as $key){
   $valArr[] = $array[$key];
}
echo $valStr = implode(",", $valArr);    
?>    

Output : apple,banana,orange 输出: apple,banana,orange

Suggestion : Use separate row for each value, to better operation. 建议 :为每个值使用单独的行,以更好地操作。 Although you have created right code to get from Comma sparate key to Value from array , but If you need it without any loop, PHP has some inbuilt functions like array_insersect , array_flip to same output 尽管您已经创建了正确的代码来从Comma sparate key Value from array ,但是如果您需要它而没有任何循环,PHP会提供一些内置函数,例如array_insersectarray_flip到相同的输出

$str = "1,2";
$arr1 = ["1"=>"test1","2"=>"test2","3"=>"test3"];
$arr2  = explode(",",$str);
echo implode(", ",array_flip(array_intersect(array_flip($arr1),$arr2)));

Live demo 现场演示

Use array_intersect_key 使用array_intersect_key

$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");

$keyarray = explode(",",$str);
echo implode(",", array_intersect_key($array, array_flip($keyarray)));

https://3v4l.org/gmcON https://3v4l.org/gmcON


One liner: 一班轮:

echo implode(",", array_intersect_key($array, array_flip(explode(",",$str))));

A mess to read but a comment above can explain what it does. 一团糟,但上面的注释可以解释它的作用。
It means you don't need the $keyarray 这意味着您不需要$ keyarray

you can try using array_filter : 您可以尝试使用array_filter

$str = "1,2,3";
$array = array("1"=>"apple", "2"=>"banana", "3"=>"orange");

$keyarray = explode(",",$str);

$filtered = array_filter($array, function($v,$k) use($keyarray){
    return in_array($k, $keyarray);
},ARRAY_FILTER_USE_BOTH);

print_r($filtered);

OUTPUT OUTPUT

Array
(
    [1] => apple
    [2] => banana
    [3] => orange
)

Another way could be using array_map() : 另一种方法是使用array_map()

echo $valStr = implode(",", array_map(function ($i) use ($array) { return $array[$i]; }, explode(",", $str)));

Read it from bottom to top: 从下至上阅读:

echo $valStr = implode(                 // 3. glue values
    ",",
    array_map(                          // 2. replace integers by fruits
        function ($i) use ($array) {
            return $array[$i];
        },
        explode(",", $str)              // 1. Split values
    )
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM