我正在计算数组的元素,并使用array_count_values将结果存储在数组中。
让我们考虑这是这个实例的输出,它是从一个数组创建的,而这个数组是在爆炸的帮助下创建的。
magazine = Array(
[avatar] => 1
[essence] => 6
[pie] => 1
[multiplex] => 1
[bill] => 2
[nice] => 2
[pie ] => 1
)
ransom = Array(
[multiplex] => 1
[pie] => 2
[avatar] => 3
[bill] => 1
[nice] => 3
[essence] => 1
)
现在,我想检查Array Magazine中是否有Array赎金中的元素。 如果赎金中的元素在杂志中不可用,则应该退出循环。 (或)如果元素存在,那么赎金中该元素的值不能大于杂志中相同的元素值。
我怎样才能做到这一点?在这种情况下如何使用嵌套的foreach?因为我不能在这里使用简单的for循环。
$ransom_temp = "avatar essence pie multiplex bill nice essence nice bill essence essence essence essence pie"
$magazine_temp = "multiplex pie pie avatar bill nice nice nice avatar essence avatar"
$magazine = explode(" ",$magazine_temp);
$ransom = explode(" ",$ransom_temp);
$countRan = array_count_values($ransom);
$countMag = array_count_values($magazine);
print_r($countMag);
print "<br>";
print_r($countRan);
if($n > $m){
print "No";
return;
}
foreach($countRan as $key1=>$value1){
foreach($countMag as $key2=>$value2)
if($key1 != $key2) || $value1 > $value2){
print "No";
return;
}
}
print "Yes";
答案 0 :(得分:3)
你只需要一个循环:
$ransom_temp = "avatar essence pie multiplex bill nice essence nice bill essence essence essence essence pie"
$magazine_temp = "multiplex pie pie avatar bill nice nice nice avatar essence avatar"
$magazine = explode(" ",$magazine_temp);
$ransom = explode(" ",$ransom_temp);
$countRan = array_count_values($ransom);
$countMag = array_count_values($magazine);
print_r($countMag);
print "<br>";
print_r($countRan);
if(count($countRan) > count($countMag)) {
print "No";
return;
}
foreach ($countRan as $key => $value){
// exit if key not exists in $countMag array
// or exit if value in $countRan[$key] greater than $countMag[$key]
if (!array_key_exists($key, $countMag) || $value > $countMag[$key]) {
print "No";
return;
}
}
print "Yes";