我有这个数组,例如:
m <- "01.2019"
sub("(\\d{2})\\.(\\d{4})", "\\2\\1", m)
#[1] "201901"
我想创建一个遍历此数组的循环并从中创建一个新数组(在这种情况下,我将检查每个键的值,并在某些情况下需要更改新数组时进行更改)。
答案 0 :(得分:0)
我为此编写了一个单独的类,您可以在“ app / Classes / NestedArray.php”中使用它
<?php
// namespace App\Classes; // DON'T FORGET TO WRITE HERE THE CORRECT NAMESPACE FOR YOU
class NestedArray
{
protected $result = [];
protected function doSomethingWith($item) {
// you can do something with $item which is not an array (string, int, or something else)
// for example, here we will collect all values which great than 10
if((int)$item > 10) {
$this->result[] = (int)$item;
}
}
protected function deepDiveIntoNextLevel(array $array) {
foreach ($array as $item) {
if(is_array($item)) {
return $this->deepDiveIntoNextLevel($item);
} else {
$this->doSomethingWith($item);
}
}
}
public function loop(array $initial_array)
{
$this->deepDiveIntoNextLevel($initial_array);
return $this->result;
}
}
在此示例中,我对不是数组的项目(假设字符串或整数)进行了处理。因此,要在应用程序中的任何位置使用此类,您只需创建一个实例并在“ loop()”函数中调用它即可。像这样:
// use App\Classes\NestedArray; // ALSO DON'T FORGET TO USE APPROPRIATE CLASS
$array = [
'foodTypes' => [
'pizza' => '120',
'burger' => [
'calorie' => '50',
'sugar' => '10',
'prices' => [
'regular' => '150',
'discount' => '10'
]
]
]
];
$nestedArray = new NestedArray();
var_dump($nestedArray->loop($array));
在此示例中,我将所有数字(数字字符串或整数)收集到一个数组中,其值大于10