Remove empty arrays from PHP variable - php

I am using PDO in order to select some values from my database. For each iteration of my $teachArray, I store the selected value into my $language_id variable. However, I am also storing some empty arrays which is not my intention.
I would like to know if it is possible to exclude or just get rid off empty arrays inside my php variable.
Here is my simple query.
$sqlFindId = "SELECT language_id
FROM language_skill
WHERE person_id = :person_id AND language_learning = :language_learning AND language_id = :language_id";
foreach ($teachArray as $dataTeach)
{
$query = $handler->prepare($sqlFindUser);
$query->bindValue(':person_id', $_SESSION['person_id']);
$query->bindValue(':language_learning', 1);
$query->bindValue(':language_id', $dataTeach);
$query->execute();
$language_id = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($language_id);
}
I use print_r on my query in order to see my variable contents.
Here are the results of my print_r. I want to get rid of the first and last arrays which are empty. It can be noted that these empty arrays can appear anywhere in my print_r.
Array ( ) Array ( [0] => Array ( [language_id] => 13 ) ) Array ( )
I have tried using
$array= array_filter(array_map('array_filter', $language_id));
but it gives the same result

foreach ($teachArray as $dataTeach)
{
$query = $handler->prepare($sqlFindUser);
$query->bindValue(':person_id', $_SESSION['person_id']);
$query->bindValue(':language_learning', 1);
$query->bindValue(':language_id', $dataTeach);
$query->execute();
$language_id = $query->fetchAll(PDO::FETCH_ASSOC);
if ( count( $language_id ) != 0 ) {
print_r($language_id);
}
}
Hope it can helps :)

Related

merge two columns into an array

I want to merge two of my columns (yanlis_cevaplar, cevap_icerik) into an array and this code here gives me only one column in array when I print it (yanlis_cevaplar).
How do I fix it?
$cevaplar = "SELECT yanlis_cevaplar FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap1 = array(); //create empty array
while ($row = $cevap_sonuc->fetch_array()) { //loop to get all results
$cevap1[] = $row; //grab everything and store inside array
}
$cevaplar2 = "SELECT cevap_icerik FROM cevaplar";
$cevap_sonuc2 = $conn->query($cevaplar) or die(mysqli_error($conn));
$cevap2 = array(); //create empty array
while ($row = $cevap_sonuc2->fetch_array()) { //loop to get all results
$cevap2[] = $row; //grab everything and store inside array
}
$tumcevaplar = array_merge($cevap1, $cevap2);
print_r($tumcevaplar);
Instead of making multiple queries, you can just fetch all the columns you want in one single query:
$cevaplar = "SELECT yanlis_cevaplar, cevap_icerik FROM cevaplar";
$cevap_sonuc = $conn->query($cevaplar) or die(mysqli_error($conn));
// Now you can fetch all the rows straight away without any loop.
// The MYSQLI_ASSOC will return each row as an associative array
$result = $cevap_sonuc->fetch_all(MYSQLI_ASSOC);
print_r($result);
This will result in something like this:
Array
(
[0] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
[1] => Array
(
[yanlis_cevaplar] => some value
[cevap_icerik] => some value
)
... and so on ..
)
If this isn't what you want, then you need to show us an example.
I also recommend that you go through some basic SQL tutorials. How SELECT works is SQL 101. Here's one of many guides: https://www.tutorialspoint.com/mysql/mysql-select-query.htm

Adding arrays to a php variable

I am using PDO in order to select some values from my database.
For each iteration of my $teachArray, I store the selected array into my $language_id variable. I then get rid of any empty array that I have inside my $language_id and assigning it to my $NoEmptyArray_language_id However, I am only storing the last array inside of $language_id in $NoEmptyArray_language_id.
I would like to concatenate every array in $language_id into $NoEmptyArray_language_id.
I cannot use $NoEmptyArray_language_id .= $language_id; since it will give me an error: Array to String conversion
Here is my simple query.
$sqlFindId = "SELECT language_id
FROM language_skill
WHERE person_id = :person_id AND language_learning = :language_learning AND language_id = :language_id";
$NoEmptyArray_language_id = "";
foreach ($teachArray as $dataTeach)
{
$query = $handler->prepare($sqlFindUser);
$query->bindValue(':person_id', $_SESSION['person_id']);
$query->bindValue(':language_learning', 1);
$query->bindValue(':language_id', $dataTeach);
$query->execute();
$language_id = $query->fetchAll(PDO::FETCH_COLUMN, 0);
if ( count( $language_id ) != 0 ) {
$NoEmptyArray_language_id .= $language_id;
}
}
print_r($NoEmptyArray_language_id);
You have to define $NoEmptyArray_language_id = array();
Also change code with $NoEmptyArray_language_id[] = $language_id;
Now you have array with values in $NoEmptyArray_language_id.
If you want to get string convert this array to string using implode function.

add values into multidimensional array

I have a foreach loop that goes through a list of items. For each of these items, I have a while loop that grabs data out of a database.
$output = array();
//$reference is a multidimensional array has been passed to this page
where the element `color` contains the color I want.
foreach ($reference as $c) {
$color = $c['color'];
$query = "SELECT DISTINCT name FROM $table where colorPreference = $color";
$exquery = mysqli_query($con, $customerQuery);
while ($row = mysqli_fetch_array($exquery)) {
$person = $row['person'];
array_push($output[$color], $person);
}
}
So this loops through, the first time searching 'red', and finding 5 people in the fake table who like red. Next, 'blue', where it finds 1 person, and then 'green' where it finds 3.
If I look at the individual results, my first array has "red, blue, green" and my second array has these lists of names.... I just don't know how to add them into an array together.
I'm trying to build an array like this:
Array
(
[Red] => Array
(
[0] => John
[1] => Sally
[2] => Bob
...
)
[Blue] => Array
(
[0] => Luke
)
[Green] => Array
(
..etc...
)
I'm not using array_push correctly though - I'm getting an Warning: Illegal offset type error. What am I doing wrong?
It's been a while since I've worked with PHP, but I think you need to initialize each "color" array that you're going to push into. So...
$output = array();
//$reference is a multidimentional array has been passed to this page
where the element `color` contains the color I want.
foreach ($reference as $c) {
$color = $c['color'];
$query = "SELECT DISTINCT name FROM $table where colorPreference = $color";
$exquery = mysqli_query($con, $customerQuery);
while ($row = mysqli_fetch_array($exquery)) {
$person = $row['person'];
if (!array_key_exists($color, $output)) {
$output[$color] = array();
}
array_push($output[$color], $person);
}
}
Try changing:
array_push($output[$color], $person);
Into:
$output[$color][] = $person;
From the manual on array_push:
Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.
Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.

convert PDO resultset array to accessible Array PHP

I am using PDO statement like below
$sql1 = "select food_typename from foodtypes WHERE 1";
$statement1 = $pdo->prepare($sql1);
$statement1->execute();
$results1 = $statement1->fetchAll(PDO::FETCH_ASSOC);
print_r($results1);
I am getting output as below:
Array
(
[0] => Array
(
[food_typename] => Punjabi
)
[1] => Array
(
[food_typename] => Indian
)
)
I want it be like
Array('Punjabi','Indian')
Any suggestions please?
If you're running PHP >= 5.5
$results = array_column($results1, 'food_typename');
If you're running earlier versions of PHP,
$results = array_map(
$results1,
function($value) {
return $value['food_typename'];
}
);
Though I don't really understand why you can't work with the original array in the first place
You can use array_map but foreach works just as well and actually runs faster than array_map for cases like this:
// Set a test array.
$results1 = array();
$results1[] = array('food_typename' => 'Punjabi');
$results1[] = array('food_typename' => 'Indian');
// Set the final reults in an array.
$results_final = array();
foreach ($results1 as $results1_value) {
$results_final[] = $results1_value['food_typename'];
}
// Dump the line array for debugging.
echo '<pre>';
print_r($results_final);
echo '</pre>';
And the output of that would be:
Array
(
[0] => Punjabi
[1] => Indian
)
The query way:
SELECT GROUP_CONCAT(food_typename), 1 AS dummy
FROM foodtypes
GROUP BY dummy
Then you need to retrieve the first field of the only record you will get back from mysql, and turn it into an array: see return group_concat data as array

How to get data from database by using $query->result() in codeigniter without foreach loop?

I have just started using CodeIgniter and want to get data from database using $query->result(), but without a foreach loop. Here is my current code:
$this->db->select('m_name');
$query1 = $this->db->get("marchant_details",1);
$rows1 = $query1->result();
However, I don't want to use a foreach loop like this, to retrieve the data:
foreach($query1->result() as $rows1)
{
$name[] = $rows1->m_name;
}
Can anyone offer an alternative solution?
I just did a quick search. I'm going to sleep, but can you try something like this:
$query->result_array();
If it doesn't work, I'll check tomorrow.
source: user-guide Maybe it will come handy.
There are two assumptions: either I misunderstood the question or the others did.
The point: by passing 1 as second parameter to $this->db->get(); method, it sets LIMIT 1 to the query and you'll get only 1 row as result.
So, why should you need to use a loop on a single row db result?
If you use $query->result(); the result would be something like:
Array
(
[0] => stdClass Object
(
[m_name] => Foo
)
)
To get the m_name value you can do the following:
$result = $query->result();
echo $result[0]->m_name;
By any reason, if you need a numeric array contains the value (as you did it in your loop) you can simply do it by $name[] = $result[0]->m_name;.
And if you use $query->result_array(); the result would be something like:
Array
(
[0] => Array
(
[m_name] => Foo
)
)
To get the m_name value you can do the following:
$result = $query->result_array();
echo $result[0]['m_name'];
But if you stop limiting the query, there are multiple rows in your query result, you can use rows1 = $query1->result_array(); instead. and array_map() to manipulate the elements of the given array:
$rows1 = $query1->result_array();
// `$row1` will be something like this:
Array
(
[0] => Array
(
[m_name] => Foo
)
[1] => Array
(
[m_name] => Bar
)
[2] => Array
(
[m_name] => Baz
)
)
Use array_map() to manipulate the result array:
function getName($array) {
return $array['m_name'];
}
$array = array_map("getName", $rows1);
print_r($array);
If you are using PHP v5.3+ you do the following:
$array = array_map(function($array) {
return $array['m_name'];
}, $rows1);
Well there is the official page in the CodeIgniter User Guide for generating DB query results depicting variations like
$row = $query->first_row()
$row = $query->last_row()
$row = $query->next_row()
$row = $query->previous_row()
If you work with CodeIgniter, its charm is that it effectively quite nicely documented.
I would assume you can go further down the abstraction layers if that's what you want, respectively you can not use the DB class but the class of your choice as custom library or whatever.
Why then are you not happy with the given possibilities, respectively how do you want to generate your query results?
you can do like this
$data=array();
$this->db->select('m_name');
$query1 = $this->db->get("marchant_details",1);
$data['name'] = $query1->result_array();
return $data;
and for more information
result_array(); // For multiple rows
row_array(); // For one row

Categories