0

I need help about combine multiple array from database and fetch with

fetchAll(PDO::FETCH_ASSOC)

first I look for data member with percentage of 90% and every data in search in database in subtract one column in query "SELECT", for example like this :

$query1 = "SELECT * FROM tb_member WHERE category = '1' AND gender = 'M' AND age = '30'";
$stmt1 = $this->db->prepare($query1);
$stmt1->execute();
$data1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);

$query2 = "SELECT * FROM tb_member WHERE category = '1' AND age = '30'";
$stmt2 = $this->db->prepare($query2);
$stmt2->execute();
$data2 = $stmt2->fetchAll(PDO::FETCH_ASSOC);

$query3 = "SELECT * FROM tb_member WHERE category = '1' AND gender = 'M'";
$stmt3 = $this->db->prepare($query3);
$stmt3->execute();
$data3 = $stmt3->fetchAll(PDO::FETCH_ASSOC);

And I combine the array with a sample code like this

$data = $data1 + $data2 + $data3;

I have tried and succeeded, but when one of the array is empty or unread it will error or not display any data even notification error

And i try make "if and else" like this

if(empty($data1)){
    $data = $data2 + $data3;
}
elseif(empty($data2)){
    $data = $data1 + $data3;
}
elseif(empty($data3)){
    $data = $data1 + $data2;
}
else{
    $data = $data1 + $data2 + $data3;
}

And page not show anything or blank, is there any other solution to solve this problem ?

UPDATE

After all i use array_merge() to combine multiple array from @Saral and when some variable is empty i use code sample like this

if(empty($array)){
    $array = array();
}

And then it's work, thank you.

2 Answers 2

1

You combine array like this

$data = array_merge($data1, $data2, $data3);

For example,

$array1 = [];
$array2 = ['a', 'b'];
$array3 = ['l', 'k', 'm'];
$array4 = [];

$array = array_merge($array1, $array2, $array3, $array4);

print_r($array);

Output:
Array ( [0] => a [1] => b [2] => l [3] => k [4] => m )

It's weird that $array = $array1+$array2+$array3+$array4; gave me Array ( [0] => a [1] => b [2] => m )

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for answering my question, i try but i dont know what happend with $data2 and i try using var_dump and result NULL, i think result of $data2 not array , can you explain this ?
@IvanJuliant PDOStatement::fetchAll returns empty array if there are zero results to fetch or false on failure: php.net/manual/en/pdostatement.fetchall.php
what should i do know if result is zero ??
0

The best way to combine array like this:

$data=compact($data1,$data2,$data3);

or

$data=array_combine($data1,$data2,$data3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.