Question

I added a sub array to the below foreach loop. Since then I get the following error which seems to refer to the trim part of my else statement:

Warning: trim() expects parameter 1 to be string, array given in C:\inetpub\wwwroot\calendarCheck\index.php ...

How can I adapt this to make it work with the sub array? Source: Add titles to items from array

My code:

$countries = '';
$valC = '';
$countC = 0;
foreach ($objDays->days as $days) {
    if(($days->dateMatch == "Yes") && ($days->locales != "")) {
        $inputC[] = array(
            "text" => explode(',', $days->locales),
            "desc" => $days->desc
        );
        $countC++;
    }
}
if($countC == 0) {
    $countries = "&nbsp;<img src='images/icons/emotion_what.png' alt='' />&nbsp;&nbsp;No data on file for this date.";
} else {
    $arrC = array_map("trim", call_user_func_array("array_merge", $inputC));
    sort($arrC);
    array_walk($arrC, function (&$valC) { $valC = "<img src='images/icons/flags-32/flag_" . str_replace(" ", "_", $valC['text']) . ".png' alt='".$valC['desc']."' id='c" . $valC['text'] . "' style='width:32px' />&nbsp;" . $valC['text']; } );
    $countries = implode(' &nbsp;&nbsp;', $arrC);
}
// ...
echo $countries;
Was it helpful?

Solution

You could alternatively do it just by building the expected output: (Untested)

<?php 
$countries = '';
foreach ($objDays->days as $days) {
    if($days->dateMatch == "Yes" && !empty($days->locales)) {
        foreach(explode(',', $days->locales) as $text){
            $countries .= "
                <img src='images/icons/flags-32/flag_".str_replace(" ", "_", $text).".png' 
                     alt='".htmlentities($days->desc)."' 
                     id='c".htmlentities($text)."' 
                     style='width:32px' />&nbsp;" . htmlentities($days->desc);
        }
    }
}

if(empty($countries)){
    echo "&nbsp;<img src='images/icons/emotion_what.png' alt='' />&nbsp;&nbsp;No data on file for this date.";
}else{
    echo $countries;
}
?>

OTHER TIPS

You can use custom function instead of trim:

$arrC = array_map(function($x) { 

    $result = array(); 
    foreach ($x as $k => $v) 
        $result[$k] = trim($v); 

    return $result;

}, call_user_func_array("array_merge", $inputC));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top