Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中,如何查找与特定键关联的值_Php_Arrays_Associative Array - Fatal编程技术网

在PHP中,如何查找与特定键关联的值

在PHP中,如何查找与特定键关联的值,php,arrays,associative-array,Php,Arrays,Associative Array,我有两个数组。一个包含id=>count,另一个包含id=>name。我试图生成一个数组,它是name=>count。有什么建议可以直接做到这一点吗 我已经查看了,但没有看到任何突出的功能可以满足我的要求,因此我猜我需要一个功能组合,但我很难想出一些不复杂的功能。类似于: foreach($countA as $id => $count) { $newArray[$nameA[$id]] = $count; } 这确实假设键在两个数组之间是对应的,因为您的要求在其他方面是不明确的

我有两个数组。一个包含
id=>count
,另一个包含
id=>name
。我试图生成一个数组,它是
name=>count
。有什么建议可以直接做到这一点吗

我已经查看了,但没有看到任何突出的功能可以满足我的要求,因此我猜我需要一个功能组合,但我很难想出一些不复杂的功能。

类似于:

foreach($countA as $id => $count)
{
    $newArray[$nameA[$id]] = $count;
}
这确实假设键在两个数组之间是对应的,因为您的要求在其他方面是不明确的。

类似于:

foreach($countA as $id => $count)
{
    $newArray[$nameA[$id]] = $count;
}
这确实假设键在两个数组之间是对应的,因为您的需求在其他方面是不明确的。

使用

编辑:以下是针对意见2中所述新需求的修订解决方案

使用

编辑:以下是针对意见2中所述新需求的修订解决方案


这假设两个数组有连续的数字键,假设两个数组大小相同。就我而言,它们不是。count数组等于或小于id/name数组。(但是,我在原始帖子中没有指定大小限制。)这假设两个数组具有连续的数字键。它假设两个数组的大小相同。就我而言,它们不是。count数组等于或小于id/name数组。(但是,我在原始发布中没有指定大小限制。)
$assocArray = array();
foreach($namesArray as $id => $name) {
    $assocArray[$name] = (array_key_exists($id, $countArray)) ? $countArray[$id] : 0;
}