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

How to get previous and next array value in php?

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

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
        )
)

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

但是使用

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

我收到了

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

所以我想要的是

希望这就是您要找的:

<?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
        )

)

您可以使用 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 demo