我有这个数组:
array:2 [▼
0 => array:3 [▼
"time" => 7780
"name" => "John A. Doe"
"photo" => "johndoe.png"
]
1 => array:3 [▼
"time" => 49800
"name" => "Jane B. Doe"
"photo" => "janedoe.png"
]
]
time
的值是秒,我的问题是如何遍历数组,以便可以运行类似以下的函数:
"time" => $this->secondsToHumanReadable(49800)
我的函数secondsToHumanReadable
已通过测试并且可以正常工作,我只希望它插入数组结果内的time
值。
更新:
所需的输出将是:
array:2 [▼
0 => array:3 [▼
"time" => '2 days, 1 hour, 3 minutes, 45 seconds'
"name" => "John A. Doe"
"photo" => "johndoe.png"
]
1 => array:3 [▼
"time" => '3 hour, 15 minutes, 20 seconds'
"name" => "Jane B. Doe"
"photo" => "janedoe.png"
]
]
答案 0 :(得分:5)
$new_array = array_map(function($item) use ($this) {
$item['time'] = $this->secondsToHumanReadable($item['time']);
return $item;
}, $my_array);
使用array_map()
的好处是返回的数组是一个新数组,因此您无需更改初始数组。通常最好不要更改数据结构
答案 1 :(得分:0)
您可以使用foreach
,如@u_mulder所说。
// Copying the original array
$result = $array;
foreach($result as $item) {
$item["time"] = $this->secondsToHumanReadable($item["time"]);
}
print_r($result);
答案 2 :(得分:0)
您可以使用 someMethod(new Bar()); // I want something similar to this that compiles, Bar adheres to Foo
someMethod(new Bar2()); // I'd like to have a compile-time error, Bar2 doesn't adhere to Foo
,但可以使用references:
foreach
输出
$data = [
[
'time' => time()
],
[
'time' => time() - 5000
]
];
foreach ($data as &$datum) {
$datum['time'] = date('d/m/Y', $datum['time']);
}
print_r($data);
实时示例
答案 3 :(得分:0)
您可以尝试
array(
"time" => function($foo){return $foo;},
"name" => "John A. Doe",
"photo" => "johndoe.png"
);