在使用foreach循环遍历数组时,可以使用键名作为索引,将两条数据放在一个键名下面。可以使用关联数组来实现这个目的。

以下是一个示例代码:

$data = [
    ['name' => 'John', 'age' => 25],
    ['name' => 'Jane', 'age' => 30],
    ['name' => 'Alice', 'age' => 28],
];

$result = [];

foreach ($data as $item) {
    $name = $item['name'];
    $age = $item['age'];

    if (!isset($result[$name])) {
        $result[$name] = [];
    }

    $result[$name][] = $age;
}

print_r($result);

输出结果:

Array
(
    [John] => Array
        (
            [0] => 25
        )

    [Jane] => Array
        (
            [0] => 30
        )

    [Alice] => Array
        (
            [0] => 28
        )

)

在上述示例中,我们创建了一个空数组$result来存储结果。然后,使用foreach循环遍历$data数组,将每个人的姓名作为键名,年龄作为值存入$result数组中。如果姓名对应的键名在$result数组中不存在,则先创建一个空数组作为该键名的值,然后将年龄追加到该数组中

php foreach的时候如何把两条数据放在一个键名下面

原文地址: http://www.cveoy.top/t/topic/iWaR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录