Php 在输出中打印分组数组键

Php 在输出中打印分组数组键,php,arrays,Php,Arrays,我有以下代码用于按大小对数组关键数据进行分组: $result = array(); foreach ($productInfo as $element) { $result[$element['size']][] = $element; } 并使用我的代码生成此分组数组: Array ( [14] => Array ( [0] => stdClass Object (

我有以下代码用于按大小对数组关键数据进行分组:

$result = array();
foreach ($productInfo as $element) {
    $result[$element['size']][] = $element;
}
并使用我的代码生成此分组数组:

Array
(
    [14] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [name] => test
                )

            [1] => stdClass Object
                (
                    [id] => 2
                    [name] => another name
                )

        )

    [6] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 3
                    [name] => name 3
                )

        )

    [4] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 4
                    [name] => name 4
                )

        )

)
我可以使用此代码显示
名称:

<?php foreach($products as $key => $product):?>
  <h5> <?= $key; ?> </h5>
<?php endforeach;?>

使用原始的
$productInfo
数组可能是一种更简单的方法,您不显示该数组,但这将在当前数组中实现。只需从当前的
$product
内爆中提取所有
name
值即可:

<?php foreach($products as $key => $product): ?>
  <h5> <?= $key; ?> </h5>
  <span> <?= implode('</span><span>', array_column($product, 'name')); ?> </span>
<?php endforeach; ?>
你需要两个周期。 假设您的阵列:

foreach ($result as $id => $items) {

    echo '<h5> ' . $id . ' </h5>';

    foreach ($items as $product) {
        echo '<span>' . $product['name'] . '</span>';
    }
}
foreach($id=>$items的结果){
回显“.$id.”;
foreach($product形式的项目){
回显'.$product['name'].';
}
}
试试这个:


如果您的
$productInfo
如下所示:

数组
(
[0]=>stdClass对象
(
[id]=>1
[名称]=>测试
[尺寸]=>14
)
[1] =>stdClass对象
(
[id]=>2
[名称]=>另一个名称
[尺寸]=>14
)
[2] =>stdClass对象
(
[id]=>3
[名称]=>名称3
[大小]=>6
)
[3] =>stdClass对象
(
[id]=>4
[名称]=>名称4
[大小]=>4
)
)
然后,您可以循环遍历每个对象并打印所需的值,如下所示:



您能提供
$productInfo
的输出吗?@HarishST:请查看我的更新。您是否试图在h5
中打印
大小,在span
中打印
名称?我想,
结果
productInfo
的输出冲突。@HarishST:u右键编辑。当然,我需要按大小分组(显示在'h5'中),并在'span'中的大小下显示名称。请查看我的更新。你有更好更简单的方法吗?实际上没有,你需要对它进行排序,然后循环并跟踪大小的变化。但是,您可以在原始循环中构建具有跨距的名称列表。第一个方法是true。第二,我不能按大小分组。
<?php foreach($products as $key => $product): ?>
  <h5> <?= $key; ?> </h5>
  <span> <?= implode('</span><span>', array_column($product, 'name')); ?> </span>
<?php endforeach; ?>
array_map(function($o) { return $o->name; }, $product)
foreach ($result as $id => $items) {

    echo '<h5> ' . $id . ' </h5>';

    foreach ($items as $product) {
        echo '<span>' . $product['name'] . '</span>';
    }
}