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;
}