php - PHP 将带有子数组值的数组连同其键一起发送到函数
问题描述
我有一个关联数组(如下所示)。我想将 $demographics['customer'] 发送到一个函数并访问数组的键和值。
function sendValues($data) {
print_r($data);
}
$demographics = array(
'customer' => array('name' => 'John', 'age' => 28),
'offers' => array('value' => '10.00', 'expiration' => '2021-10-01')
);
//print_r($demographics);
sendValues($demographics['customer']);
实际的:
Array
(
[name] => John
[age] => 28
)
预期的:
Array
(
[customer] => array(
[name] => John
[age] => 28
)
)
解决方案
如果您只需要将数组的特定部分发送给函数,您也可以使用array_slice()
. 就像这样的第一个元素:
sendValues(array_slice($demographics, 0, 1));
另请参阅:https ://www.php.net/manual/en/function.array-slice.php