Using this sample multidimensional array (of a palette which contains colours, which in turn contains their respective shades), let’s say I would like to display the colours in an imploded list (comma-separated) and, if applicable, its respective shades in brackets, also in an imploded (comma-separated) list.
I can easily implode the inner array (shades), but cannot figure out how to do that with the outer array (colours) given it contains the array of shades which must be run through for each colour.
I’ve seen there are several solutions for imploding a multidimensional array, but these seem to be without requiring running through a possible inner array for each. Perhaps there is another method by which to separate the entries with a comma?
And while I’m on the subject, is there a way of replacing the last comma of an imploded string with ‘and’?
Thanks in advance.
$sql = "SELECT DISTINCT colour_id, colour_nm, colour_url
FROM palettecolours
INNER JOIN colour ON colourid = colour_id
WHERE paletteid = '$palette_id'";
while ($row = mysqli_fetch_array($result))
{
$colour = '<a href = "/colour/' . $row['colour_name'] . '">' . $row['colour_url'] . '</a>';
$colours[$row['colour_id']] = array('colour' => $colour, 'shades' => array());
}
$sql = "SELECT colourid, shade_name, shade_url
FROM palettecolours
INNER JOIN shade ON shadeid = shade_id
WHERE paletteid = '$palette_id'";
while ($row = mysqli_fetch_array($result))
{
$shade = '<a href = "/shade/' . $row['shade_name'] . '">' . $row['shade_url'] . '</a>';
$colours[$row['colourid']]['shades'][] = array('shade' => $shade);
}
<?php foreach ($colours as $colour): ?>
<?php echo $colour['colour']; ?>
<?php if(!empty($colour['shades'])) { ?>(<?php echo implode(", ", $colour['shades']); ?>)<?php } ?>
<?php endforeach; ?>
CURRENT DISPLAY:- Red (Magenta, Burgundy, Crimson) Blue Green Yellow (Egyptian Cotton, Magnolia) White (Soft Moon)
DESIRED OUTCOME:- Red (Magenta, Burgundy, Crimson), Blue, Green, Yellow (Egyptian Cotton, Magnolia), White (Soft Moon)
How about recursive functions? Something like
function array_implode_recursive($glue, $data, $before = '(', $after = ')') {
//Loop through every child and check whether it is an array or not and implode it if so
foreach($data as &$element) {
if (is_array($element)) {
$element = $before . array_implode_recursive($glue, $element) . $after;
}
}
//It's really safe to erase this variable as sometimes PHP has fun with them
unset($element);
return implode($glue, $data);
}
Use it like this
$mydata = implode_recursive(', ', $data);
$mydata = implode_recursive(', ', $data, '[', ']');
Hope it helped
Since you know what your array looks like and it appears to have keys you could try something similar to what I've done here.