这里我有数组,在这个数组中studentAbsentId我有一个更多的数组,现在我想找到studentAbsentId 1意味着他的名字,假设studentAbsentId 2意味着他的名字,所以我写了一个函数helper.php ,但它是抛出错误,如何解决这个问题。
我的控制器
public function getAbsentListStaff() {
$data = array(
"schoolId" => $_POST['schoolName'],
"classId" => $_POST['className'],
"sectionId" => $_POST['sectionName'],
"studentAbsentDate" =>$_POST['studentAbsentDate'],
);
$absentresponse= $this->Android_login_model->admin_options_listdisplayStaff($data);
foreach($absentresponse as $absent){
echo $id = $absent['studentAbsentId'];
//echo getStudentnameById($id);
}
}
的print_r($ absentresponse);
Array
(
[0] => Array
(
[absent_id] => 1
[studentAbsentId] => 3
[studentAbsentDate] => 2017-04-20
[schoolId] => 2
[classId] => 1
[sectionId] => 1
[morning] => 1
[evening] => 1
[updatedBy] => 1
[updatedOn] => 2017-04-20
[status] => 0
)
[1] => Array
(
[absent_id] => 2
[studentAbsentId] => 4
[studentAbsentDate] => 2017-04-20
[schoolId] => 2
[classId] => 1
[sectionId] => 1
[morning] => 1
[evening] =>
[updatedBy] => 1
[updatedOn] => 2017-04-20
[status] => 0
)
[2] => Array
(
[absent_id] => 3
[studentAbsentId] => 5
[studentAbsentDate] => 2017-04-20
[schoolId] => 2
[classId] => 1
[sectionId] => 1
[morning] => 1
[evening] =>
[updatedBy] => 1
[updatedOn] => 2017-04-20
[status] => 0
)
)
helper.php /在帮助文件夹下
if ( ! function_exists('getStudentnameById')){
function getStudentnameById($id){
$ci =& get_instance();
$ci->load->database();
$ci->db->select('firstName');
$ci->db->where('student_id', $id);
$q = $ci->db->get('new_student')->result();
return $q[0]->firstName; // particulart filed
}
}
从这里开始如果我打印studentAbsentId意味着它正在工作,但是我需要那个id的名字,怎么能解决这个问题?
答案 0 :(得分:0)
更改此项(在getStudentnameById
函数中)
return $q[0]->firstName;
如下
$first_name = isset($q[0]->firstName) ? $q[0]->firstName : '';
return $first_name;
因为您的循环将继续3次,因为您的数组中有3个元素,但在new_student
表数据可能不适用于每个$id
,那么它将通过错误。一旦您通过isset()
进行检查,它将仅在找到的数据时返回数据,否则将返回空字符串。
但是,如果找不到像
这样的数据,您可能会返回任何演示数据$first_name = isset($q[0]->firstName) ? $q[0]->firstName : 'no name';
另一种方式
试试这个
if ( ! function_exists('getStudentnameById')){
function getStudentnameById($id){
$ci =& get_instance();
$ci->load->database();
$ci->db->select('firstName');
$ci->db->where('student_id', $id);
$q = $ci->db->get('new_student')->result();
if(!empty($q)){
$first_name = $q[0]->firstName;
}else{
$first_name = 'no data';
}
return $first_name;
}
}