phparrayscodeigniterarray-mergearray-push

MySQL and push query array together


I have this code here

$sql_array = array();
if($result['user_id'] == 'OA'){
                $sql = "select distinct id, FirstName, LastName from table_one ti left join table_two sp on (sp.user_id = ti.id) or (sp.user_id = ti.id)";
                $query = $this->db->query($sql);
                $results_array = $query->result_array();
                $sql_array = array_push($sql_array, $results_array);
            }
            elseif($result['user_id'] == 'SH'){
                $sql = "select distinct id, first_name, last_name from table_three teo left join table_two sp on sp.user_id = teo.id";
                $query = $this->db->query($sql);
                $results_array = $query->result_array();
                $sql_array = array_push($sql_array, $results_array);
            }elseif($result['user_id'] == 'OF'){
                $sql = "select distinct id, first_name, last_name from table_four os left join table_two sp on sp.user_id = os.id";
                $query = $this->db->query($sql);
                $results_array = $query->result_array();
                $sql_array = array_push($sql_array, $results_array);
            }elseif($result['user_id'] == 'US'){
                $sql = "select distinct ID, substring_index(display_name, ' ', 1) as 'FirstName', substring_index(display_name, ' ', -1) as 'LastName' from table_five tu left join table_two sp on sp.user_id = tu.id";
                $query = $this->db->query($sql);
                $results_array = $query->result_array();
                $sql_array = array_push($sql_array, $results_array);
            }

Its going through all of the $result['user_id'] and see which query string to run base on what $result['user_id'] is....With the code above I got an error array_push() expects parameter 1 to be array, integer given

What Am I doing wrong or is there a better way to do this?

Thanks, J


Solution

  • Why don't you use the [] syntax?

    if($result['user_id'] == 'OA'){
                $sql = "select distinct id, FirstName, LastName from table_one ti left join table_two sp on (sp.user_id = ti.id) or (sp.user_id = ti.id)";
                $query = $this->db->query($sql);
                $results_array = $query->result_array();
                $sql_array[] = $results_array;
            }
    

    about the reason of your error it is because you affect the return of array_push to your array variable. The problem is that array_push returns an integer so on the second turn of the loop you will try to pass an integer as first param of array_push