[英]Is there an PHP function to get values from an array which is inside another array?
到目前为止,我一直在使用函数array_values
将这些值放入另一个变量中。 但是现在我有一个数组在另一个数组中,所以我想知道是否可以仅通过使用函数(而不是使用foreach loop
)来获取该数组的值?
这是我正在谈论的代码示例:
public function returnArrayElements() {
$array_one = ['positive' => [], 'negative' => []];
$array_two = [1, -1, 2, -2, -3, -4, 5];
foreach($array_two as $element) {
if ($element > 0) {
$array_one['positive'][] = $element;
} else {
$array_one['negative'][] = $element;
}
}
return [
'pos' => array_values(array_values($array_one['positive'])),
'neg' => array_values(array_values($array_one['negative'])),
];
}
在array_values
函数中使用array_values
函数合法吗? 或者有没有更好的方法来做到这一点?
编辑:
如您所见,这是简化的代码,当然我不会在实际情况中这样使用它。 关键是$array_one
更大,并且有很多不同的元素,其中一个是另一个数组。 数组作为参数传递给正在使用它们的函数(我在我的问题中没有这样写,因为我认为它现在并不重要)。 现在想象一下,在代码中的某个地方,我只需要数组中用作另一个数组中元素的那些值,这就是为什么我需要函数只返回这些元素而不是整个$array_one
,因为该函数所在的代码部分被调用只知道如何处理来自$array_two
元素。
这是一个新的代码示例:
$array_one = [
[
'1' => 'el1',
'2' => 'el2',
'3' => [
'3.1' => 'el3.1',
'3.2' => 'el3.2',
'3.3' => 'el3.3',
],
'4' => 'el4',
'5' => 'el5',
],
[
'1' => 'el1',
'2' => 'el2',
'3' => [
'3.1' => 'el3.1',
'3.2' => 'el3.2',
'3.3' => 'el3.3',
],
'4' => 'el4',
'5' => 'el5',
]];
function one($array_one) {
//knows how two work with whole $array_one
}
function two(array_values(array_values($array_one))) {
//knows only how to work with el3.1, el3.2, el3.3
//in this function is not implemented the code
//which is going to get those three elements from $array_one
}
我在上面的两个不同数组中写入了相同的元素,但这只是因为我再也想不出别的东西了。 在实际系统中,这些数组是不同的,只是array_key
3
始终具有相同的名称(在实际系统中,它的名称不是3
,而是property_data
)。
编辑2:
真实代码的图像。 我需要property_data
这3 个元素,它们都放在一个变量(一个数组)中。 如果没有 foreach 循环,是否可以做到这一点?
你可以这样做:
// will print the first element of $array_two
echo $array_two[0];
> 1
或者你可以只使用print_r():
print_r($array_two);
> Array ( [0] => 1 [1] => -1 [2] => 2 [3] => -2 [4] => -3 [5] => -4 [6] => 5 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.