Skip to content
Advertisement

Multidimensional associative array group, filter and echo

could someone please give me several hints? No matter if I try it with array_column, array_push, array_filter, array_diff … somewhere along the way I ALWAYS make a mistake.

I want to group a multidimensional associative array, filter it and echo the groups.

My array e.g. is:

$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 €'
    ],
];

I want to group by producer/Hersteller – by filtering it into a new array, delete the new arrays from the original array and echoing each array.

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

…and echo each array with foreach ($cars2 as $car) { echo ”. ‘Hersteller: ‘ . $cars2[‘Hersteller’] …

My problem is (primarily) with array_diff!

Advertisement

Answer

As array_diff() doesn’t work very well with multidimensional arrays (it likes to work with strings), you could use array_udiff() which means you have to write your own comparison. But thanks to the spaceship operator (<=>) you can compare the values using this…

$cars4 = array_udiff($cars, $cars2, $cars3, function ( $a, $b) {
    return $a <=> $b;
});
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement