如何获取数组列表中 object 中的键和值

how to get the key and value in the object in list of array

如何获取 object 列表中的不同键($key)和多个不同值($myObjectValues)?

我的预期结果是不同的键显示为 table 中的列,其不同的值显示为多行。列 ($key) 不应该是硬核的,我打算在 blade 视图中显示。

理想:

当前代码:

foreach($x as $key => $item) {

    print_r($key); //this is list number

    foreach($item as $key => $myObjectValues){

        print_r($key); //this is my object key
        print_r($myObjectValues); //this is my object values
    }
}

这是 json 数组 object ($x)。

Array(
[0] => stdClass Object
    (
        [milk_temperature] => 10
        [coffeebean_level] => 124.022
    )

[1] => stdClass Object
    (
        [milk_temperature] => 1099
        [soya_temperature] => 10
        [coffeebean_level] => 99.022
    )

[2] => stdClass Object
    (
        [milk_temperature] => 1099
        [coffeebean_level] => 99.022
    )
)

你可以这样做,这不是世界上最好的方法,但它有效,你可以将其用作示例。首先,您创建一个包含 table header 标题的列表,然后开始打印 header,然后打印值。

<?php

$x = [
    (object) [
        'milk_temperature' => 10,
        'coffeebean_level' => 124.022
    ],
    (object) [
        'milk_temperature' => 1099,
        'soya_temperature' => 10,
        'coffeebean_level' => 99.022
    ],
    (object) [
        'milk_temperature' => 1099,
        'coffeebean_level' => 99.022
    ]
];

// list all the keys
$keys = [];
foreach($x as $key => $item) {
    $keys = array_merge($keys, array_keys((array) $item));
}

$keys = array_unique($keys);

// echo the header
foreach ($keys as $key) {
    echo $key . ' ';
}
echo "\n";

// echo the values
foreach($x as $item) {
    foreach ($keys as $key) {
        echo $item->$key ?? '-'; // PHP 7+ solution
        // echo isset($item->$key) ? $item->$key : '-'; // PHP 5.6+
        echo ' ';
    }

    echo "\n";
}

你可以先用array_keys()array_collapse()得到数组的键:

$columns = array_keys(array_collapse($records));

然后您使用您已有的相同循环查看 $records。让我们用这个例子来演示它:

    $columns = array_keys(array_collapse($records));

    foreach($records as $key => $item) {

        //these are each record
        foreach ($columns as $column) {
            //each column where you build the header

            // converts $item to an array
            $item = (array)$item;

            if (! array_key_exists($column, (array)$item)) {
                // show '---'
                echo '---';
                continue;
            }
            //show $item[$item]
            echo $item[$column];
        }
    }

这样做的最大好处是首先获取列(除了将 stdClass 转换为数组之外)是列数组可以以您认为合适的任何方式使用。

It would be more beneficial if you can have your data all as array then you can easily use the array functions available on it.