猿问

从第一个数组返回键值,其键在第二个数组中

我有两个数组,我想从第一个数组中仅通过键搜索我在第二个数组中拥有的数组,作为第三个数组,我想打印结果:

$colldata=array("bench-press-rod"=>'',"adidas-classic-backpack"=>'93549559913',"adidas-classic-backpack-legend-ink-multicolour"=>'',"puma-suede-classic-regal"=>'93549920361,93549723753');
$colldata2=array(0 => 'bench-press-rod',1 => 'adidas-classic-backpack');

预期结果:

array('bench-press-rod'=>'',"adidas-classic-backpack"=>'93549559913');


素胚勾勒不出你
浏览 161回答 3
3回答

宝慕林4294392

您可以在 PHP 中的一行中执行此操作,array_flip用于交换第二个数组的键和值,然后array_intersect_key在匹配的键上合并两个数组:$colldata=array("bench-press-rod"=>'',"adidas-classic-backpack"=>'93549559913',"adidas-classic-backpack-legend-ink-multicolour"=>'',"puma-suede-classic-regal"=>'93549920361,93549723753');$colldata2=array(0 => 'bench-press-rod',1 => 'adidas-classic-backpack');print_r(array_intersect_key($colldata, array_flip($colldata2)));输出:Array(    [bench-press-rod] =>     [adidas-classic-backpack] => 93549559913)3v4l.org 上的演示

一只斗牛犬

我能想到的最简单的方法是遍历第二个数组并将第一个数组中的匹配键添加到输出中。如果该项目不存在,则它会放入Not found输出...$output = [];foreach ( $colldata2 as $item ) {    $output[$item] = $colldata[$item] ?? 'Not found';}print_r($output);给..Array(    [bench-press-rod] =>     [adidas-classic-backpack] => 93549559913)

撒科打诨

检查这个。$colldata=array("bench-press-rod"=>'',"adidas-classic-backpack"=>'93549559913',"adidas-classic-backpack-legend-ink-multicolour"=>'',"puma-suede-classic-regal"=>'93549920361,93549723753');$colldata2=array(0 => 'bench-press-rod',1 => 'adidas-classic-backpack');$result = [];foreach ($colldata2 as $key => $value) {&nbsp; &nbsp; if (array_key_exists($value, $colldata)) {&nbsp; &nbsp; &nbsp; &nbsp; array_push($result,$colldata[$value]);&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;}echo '<pre/>';print_r($result);
随时随地看视频慕课网APP
我要回答