我有一个大的50个值的大数组(例如我使用较小的数组):
Array
(
[Adam Małysz] => 1
[Justyna Kowalczyk] => 2
[Janne Ahonen] => 3
[Stefan Hula] => 4
[Ole Einar Bjoerdalen] => 5
[Jakub Janda] => 6
[Mariusz Pudzianowski] => 7
[Harry Potter] => 8
[Vladimir Zografski] => 9
[Pavel Karelin] => 10
[Eddie Edwards] => 11
[Apoloniusz Tajner] => 12
)
我有 n 具有不同值的较小常量数组:
Array
(
[Adam Małysz] => 1
[Janne Ahonen] => 2
[Stefan Hula] => 3
[Ole Einar Bjoerdalen] => 4
[Vladimir Zografski] => 5
[Pavel Karelin] => 6
[Apoloniusz Tajner] => 7
[Mariusz Pudzianowski] => 8
[Jakub Janda] => 9
[Harry Potter] => 10
)
Array
(
[Justyna Kowalczyk] => 1
[Apoloniusz Tajner] => 2
[Harry Potter] => 3
[Janne Ahonen] => 4
[Mariusz Pudzianowski] => 5
[Adam Małysz] => 6
[Jakub Janda] => 7
[Ole Einar Bjoerdalen] => 8
[Vladimir Zografski] => 9
[Pavel Karelin] => 10
)
Array
(
[Adam Małysz] => 1
[Janne Ahonen] => 2
[Jakub Janda] => 3
[Stefan Hula] => 4
[Ole Einar Bjoerdalen] => 5
[Justyna Kowalczyk] => 6
[Harry Potter] => 7
[Mariusz Pudzianowski] => 8
[Vladimir Zografski] => 9
[Apoloniusz Tajner] => 10
)
所以我想减去数组值,其中的相同键是:
Big Array:[哈利波特] => 8
[Mariusz Pudzianowski] => 7小阵列#1:[哈利波特] => 10个
[Mariusz Pudzianowski] => 8
小阵列#2:[哈利波特] => 3
[Mariusz Pudzianowski] => 5输出:小数组#1和大数组之间的关键[哈利 波特] = 2
密钥[Mariusz Pudzianowski]的小数组#1和大数组之间的差异= 1输出:小阵列#2之间的差异 关键的大数组[哈利波特] = 5
小数组#2和大数组之间的关键[Mariusz Pudzianowski] = 2
基本上我被卡住了。 请帮忙。
答案 0 :(得分:0)
允许将您的大数组命名为$ bigArray,将小数组命名为$ smallArray,它们都具有键值对。现在代码应该是:
foreach($bigArray as $bigKey=>$bigValue){
foreach($smallArray as $smallKey=>$smallValue){
if($smallKey==$bigKey){
$output=$bigValue-$smallValue;
echo 'Difference between Small Array #1 and Big Array for $bigKey is '.$output;
}
}
}
这样对于大数组的每个元素,你将循环小数组并检查键是否匹配,如果它们匹配,那么你减去它们的值并打印它们。您也可以为其他小型数组执行此操作。
答案 1 :(得分:0)
您可以使用array_intersect_key查找所有阵列通用的所有密钥。
$commonKeys = array_intersect_key($bigArray, $smallArray1, $smallArray2, ...)
从那里你只需要迭代$ commonKeys并进行适当的替换。类似的东西:
foreach ($commonKeys as $key) {
$result = abs($bigArray[$key] - $smallArray1[$key]);
echo " Difference between Small Array #1 and Big Array for key [$key] = $result";
//you do that for each Small Array
}