鉴于以下数组,如何优雅地验证该选项,价格和成本数组是否具有匹配的键值?
Array
(
[option] => Array
(
[1] => C
[2] => M
[3] => G
)
[price] => Array
(
[1] => 100
[2] => 200
[3] => 300
)
[cost] => Array
(
[1] => 0
[2] => 0
[3] => 0
)
)
我想在每个阵列上运行 foreach(数组为键=>值)并将这些值发送到另一个数组,然后使用 if(!in_array),但这是一个更好的方法。
答案 0 :(得分:2)
听起来你想要相同的键,因为与数组中的值没有相关性。如果是这样,您可以在每个子数组的键上运行diff:
if(call_user_func_array('array_diff_key', $array)) {
// not the same keys
} else {
// same keys
}
call_user_func_array()
将数组作为参数数组,并将每个数组传递给array_diff_key()
答案 1 :(得分:0)
我建议以这种方式使用数组:
Array ( [option] => Array ( [C] => Array ( [price] => 100 [cost] => 0 ) [M] => Array ( [price] => 200 [cost] => 0 ) [G] => Array ( [price] => 300 [cost] => 0 ) ) )
PHP代码:
$product = array("option" => array("C" => array("price" => 100, "cost" => 0), "M" => array("price" => 200, "cost" => 0), "G" => array("price" => 300, "cost" => 0)));