简体   繁体   中英

How to replace blank or empty values in array of arrays in PHP

How can I replace empty values in an array of arrays in PHP? I have the result below with my var_dump .

array(2) {
[0]=>
   object(stdClass)#979 (5) {
     ["class"]=>
     string(0) ""
     ["date"]=>
     string(10) "2018-07-01"
   }
[1]=>
   object(stdClass)#1057 (5) {
      ["class"]=>
      string(0) ""
      ["date"]=>
      string(10) "2018-07-02"

}

Array size is not in a fixed length. This is my result using my query which the code is below:

$classname = "employee.class";
$date = "attendance.date";
$classCollection=[];
for($i = 1; $i<32; $i++){
    if($i<10) $i = '0'.$i;
    $class = DB::table('attendance')
           ->leftJoin('employee','employee.key','=','attendance.key')
           ->select($classname,$date)
           ->where(DB::raw("DATE_FORMAT(attendance.date,'%Y-%m-%d')"), '=', '2018-07'.'-'.$i);
           ->get();

    $classCollection = array_merge($classCollection, $class->toArray());

    //I tried doing this way, but I think I'm missing something?
    foreach($classCollection as &$val){
       if($val === "" ) $val = "unassigned";
    }
}

I just want to replace class that are empty with some string like unassigned .Any inputs are appreciated.

Insert this after array or object where you getting array or objects.

foreach ($ur_result as $key => $value) {
        sanReplaceNull($ur_result[$key]);
}


function sanReplaceNull($array){
    if (is_object($array)) {
        foreach ($array as $key => $value) {
            if (is_null($value) || $value='') {
                 $array->$key = 'unassigned';
            }
        }
    }else{
        $array = array_map(function($value) {
           return $value === "" ? 'unassigned' : $value;
        }, $array); 
    }
    return $array; 
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM