【问题标题】:Multidimensional associative array group, filter and echo多维关联数组组、过滤和回显
【发布时间】:2020-01-27 12:08:28
【问题描述】:

有人可以给我几个提示吗?无论我是否尝试使用 array_column、array_push、array_filter、array_diff ......在某个地方我总是会犯错误。

我想对一个多维关联数组进行分组,对其进行过滤并回显这些组。

我的数组,例如是:

$cars = [
    ['Hersteller' => 'Audi',
        'Modell' => 'Btron',
        'Preis' => '60.000 €'
    ],
    ['Hersteller' => 'Tesla',
        'Modell' => 'Unununium',
        'Preis' => '5.000 €'
    ],
    ['Hersteller' => 'Audi',
        'Modell' => 'Quattro',
        'Preis' => '40.000 €'
    ],
    ['Hersteller' => 'Opel',
        'Modell' => 'Astra',
        'Preis' => '20.000 €'
    ],
    ['Hersteller' => 'Abba',
        'Modell' => 'Golf',
        'Preis' => '2.000 €'
    ],
    ['Hersteller' => 'Lamborghini',
        'Modell' => 'Diablo',
        'Preis' => '95.000 €'
    ],
    ['Hersteller' => 'Tesla',
        'Modell' => 'Roadster',
        'Preis' => '65.000 €'
    ],
];

我想按生产者/Hersteller 进行分组 - 通过将其过滤到新数组中,从原始数组中删除新数组并回显每个数组。

$cars2 = [];
$cars3 = [];
$cars4 = [];
$cars2 = array_filter($cars, function ($var) {
    return ($var['Hersteller'] == 'Audi');
});
$cars3 = array_filter($cars, function ($var) {
    return ($var['Hersteller'] == 'Tesla');
});

$cars4 = array_diff($cars, $cars2, $cars3);

...并使用 foreach ($cars2 as $car) { 回声''。 '赫斯特勒:' 。 $cars2['Hersteller'] ...

我的问题(主要)是array_diff!

【问题讨论】:

  • 显示所需的输出。

标签: php multidimensional-array associative


【解决方案1】:

由于array_diff() 不适用于多维数组(它喜欢处理字符串),您可以使用array_udiff(),这意味着您必须编写自己的比较。但是感谢宇宙飞船操作员 (<=>),您可以使用它来比较值...

$cars4 = array_udiff($cars, $cars2, $cars3, function ( $a, $b) {
    return $a <=> $b;
});

【讨论】:

  • 谢谢!我错过了!效果很好!
猜你喜欢
  • 1970-01-01
  • 2019-10-26
  • 2011-08-15
  • 2018-11-15
  • 2018-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多