如何在php中获取上一个和下一个数组值



所以我使用RapidAPI的API,在json_encode((it-之后,我得到下面的数组

Array
(
[00:00:00] => Array
(
[name] => Arr Name 1
[other-details] => Arr Desscription 1
[type] => Arr Type 1
)
[00:30:00] => Array
(
[name] => Arr Name 2
[other-details] => Arr Desscription 2
[type] => Arr Type 2
)
)

既然您已经看到了我从现在开始得到的结构,请注意,我只得到了开始时间I.e[00:00],而不是结束时间,即它应该是[0:0:00]结束时间。

但是使用

foreach ($arr as $key => $value) { 
}

我得到

  • [00:00:00]
  • [00:30:00]

正如你在foreach中所期望的那样,我曾尝试使用array_slice在foreach内部使用foreach,但失败了。

所以我想要的是

  • 开始时间-结束时间
  • [00:00:00][00:30:00]
  • [00:30:00]

您可以使用array_keys从数组中获取并循环键。

在循环中,通过检查数组中下一个值的键是否存在,打印开始时间,如果存在,则只打印结束时间。

$a = [
'00:00:00' => [
'name' => 'Arr Name 1',
'other-details' => 'Arr Desscription 1',
'type' => 'Arr Type 1'
],
'00:00:30' => [
'name' => 'Arr Name 2',
'other-details' => 'Arr Desscription 2',
'type' => 'Arr Type 2'
],
'00:01:00' => [
'name' => 'Arr Name 3',
'other-details' => 'Arr Desscription 3',
'type' => 'Arr Type 3'
],
'00:01:30' => [
'name' => 'Arr Name 4',
'other-details' => 'Arr Desscription 4',
'type' => 'Arr Type 4'
]
];
$keys = array_keys($a);
for ($i = 0; $i < count($keys); $i++) {
$result = $keys[$i];
if (array_key_exists($i+1, $keys)) {
$result .= " " . $keys[$i + 1];
}
echo $result . PHP_EOL;
}

输出

00:00:00 00:00:30
00:00:30 00:01:00
00:01:00 00:01:30
00:01:30

查看PHP演示

我希望这就是您想要的:

<?php
// sample data
$data = [

"00:00:00" => [
"name" => "Test name",
"details" => "Test details",
"type" => "Test type"
],

"00:30:00" => [
"name" => "Test name",
"details" => "Test details",
"type" => "Test type"
],

"00:60:00" => [
"name" => "Test name",
"details" => "Test details",
"type" => "Test type"
]

];
$timeslots = [];
foreach(array_chunk($data, 2, TRUE) as $key => $value) {

$timeslots[] = array_keys($value);
}
print_r($timeslots);
?>

输出:

Array
(
[0] => Array
(
[0] => 00:00:00
[1] => 00:30:00
)
[1] => Array
(
[0] => 00:60:00
)
)

相关内容

最新更新