How to change php array output - php

I have the following function:
public function albums($artist) {
$artist = $this->db->sanitize($artist);
$query = "
SELECT `album`, `cover`
FROM `albums`
join `artists`
on `albums`.`artistsID` = `artists`.`id`
WHERE `artists`.`artist` = ?
";
$stmt = $this->db->mysqli->prepare($query);
$stmt->bind_param('s', $artist);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
return $data;
}
As you can see this will return an array with the album name and the cove file path.
The array output looks like this:
Array
(
[0] => Array
(
[album] => Album name
[cover] => file path
)
[1] => Array
(
[album] => Album name
[cover] => file path
)
)
As you can see it returns an array with 0 and 1 with an array of album and cover.
What I would like it to be is an array which is easier to use with a while loop.
So I can do something like:
while($row = $data) {
echo $row['album'].' <img src="'.$row['cover'].'">';
}
instead of 2 foreach loops like I have to do now. So my question is how can I get an array which is easier to use like you would normaly get when you do something like:
<?php
$query = mysqli_query($connect, "SELECT `username` FROM `users` WHERE `id` = 1");
while($row = mysqli_fetch_assoc($query)) {
echo $row['username'];
} //Just as an example to make the question a bit more understandable
?>
I hope someone could help me out on this one. If you need more information please let me know.

What I would like it to be is an array which is easier to use with a while loop
You should rather use a foreach loop for this … then the whole “problem” solves itself without any further meddling with the array structure.

You're using fetch_assoc() so...
while($row = $result->fetch_assoc()) {
echo $row['album'] . ' <img src="' . $row['cover'] . '">';
}

Related

Add multiple SQLresults to an array while in a foreach loop

I am having some trouble trying to get this done. The issue is:
I have an array that looks like
wants_arr_flat ( [0] => booze [1] => nudes [2]
=> rooms
I want my foreach loop to go through these values making a different SQL statement and then saving the result of that SQL statement on to another array. The code I am trying to work with now is this.
foreach ( $wants_arr_flat as $value ) {
$sql = "SELECT * FROM offers WHERE user_id != $_SESSION[user_id] AND offer='$value'";
$result=$conn->query($sql);
$want_match_arr = mysqli_fetch_row($result);
echo '<pre>'; print_r($want_match_arr); echo '</pre>'; //testing echo
Obviously this is just overwriting the last array each iteration so I only end up with one result in the array.
instead of
$want_match_arr = mysqli_fetch_row($result);
use
$want_match_arr[] = mysqli_fetch_row($result);
If you get multiple rows from SQL then this is better.
$want_match_arr = [];
foreach ( $wants_arr_flat as $value ) {
$sql = "SELECT * FROM offers WHERE user_id != $_SESSION[user_id] AND offer='$value'";
$result=$conn->query($sql);
while ($row = mysql_fetch_assoc($result)) {
$want_match_arr[] = $row;
}
}
echo '<pre>'; print_r($want_match_arr); echo '</pre>'; //testing echo

Make Associative array with three element in array

I want three element in associative array, so far am successful in getting two in the array.
$sql = "SELECT * FROM `notification_table` ";
$resultsd1 = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($resultsd1);
$associativeArray = array();
while ($row = mysqli_fetch_assoc($resultsd1))
{
$associativeArray[$row['name']] = $row['price'] ;
}
foreach($associativeArray as $k => $id){
echo $k."=>".$id .' ';
}
And am getting the response like this
name1=>24.725 name2=>24.265
Now i want to add another column in array as well and the name is column is notification_check .
Am not able to get how to add three columns in a single array. Any help will be appreciated.
I want the output like name1=>24.725=>yes_notification name2=>25.43=>no_notification
And when i print_r($row) is show this output Array ( [sno] => 1 [name] => name1 [price] => 23 [notification_check] => yes_notification)
You could shorten this and use mysqli_fetch_all to create an array of all of the data and then manipulate the array using array_column to create the index...
$result = mysqli_fetch_all($resultsd1, MYSQLI_ASSOC);
$associativeArray = array_column($result, null, 'name');

foreach is not working while trying to get students

echo "<pre>"; print_r($jobbrnchesids); exit;
<pre>Array
(
[0] => Array
(
[id_branch] => 6
)
[1] => Array
(
[id_branch] => 1
)
)
From the above array, i am getting job id branches.. Now i am trying to Get the students who are with these branches.
i have tried like this way but it something is going wrong unable to debug can anyone help me out.
$studentBranch = '';
foreach ($jobbrnchesids as $k => $v){
$stuBranch = $conn->query("SELECT student_pid FROM tbl_students
WHERE graduation_branch = ".$v." ");
$studentsWithBranches[] = $stuBranch->fetch_assoc();
}
echo "<pre>"; print_r($studentsWithBranches); exit;
instead of $v it need to be $v['id_branch']
missing array index 'id_branch'
Try:
$stuBranch = $conn->query("SELECT student_pid FROM tbl_students
WHERE graduation_branch = ".$v['id_branch']." ");
Reduce your overhead by doing the following:
$branchIds = array_column($jobbrnchesids,"id_branch");
$result = $conn->query("SELECT student_pid FROM tbl_students
WHERE graduation_branch IN (".implode(",",$branchIds.")");
$studentsWithBranches = $result?$result->fetch_all(MYSQLI_ASSOC):[];
array_column Returns the values from a single column in the input array
$studentBranch = '';
foreach ($jobbrnchesids as $k => $v) {
$stuBranch = $conn->query("SELECT student_pid FROM tbl_students WHERE graduation_branch = '" . ['id_branch'] . "'");
$studentsWithBranches[] = $stuBranch->fetch_assoc();
}
echo "<pre>";
print_r($studentsWithBranches);
exit;

Problems with array error

Hello stackoverflow people, can you help me with this error,
Warning: array_combine() expects parameter 2 to be array, null given
in
$check = mysql_query("SELECT user_task_types, user_task_types_id FROM dotp_user_task_type WHERE user_id = '$user_id'");
$row[] = mysql_fetch_array($check);
$check = array_combine($row[0], $row[1]);
Cant understand what is wrong with it. Ive tried doing [] this so it would be array but still nothng. My array looks like this:
Array
(
[0] => TVS darbai
[user_task_types] => TVS darbai
[1] => 14
[user_task_types_id] => 14
)
I want to connect user task type id with user task types it would look like [14] => TVS darbai
$row[] = appends to an array. Your array now looks like:
array(
0 => array(...)
)
As you see, there's no [1]. You probably just want $row = mysql_fetch_array(..), then $row[0] corresponds to the first column and row[1] to the second. It would still not make sense to array_combine those two columns though.
You probably want this:
$result = mysql_query(...);
$check = array();
while ($row = mysql_fetch_array($result)) {
$check[$row[0]] = $row[1];
}
You no need to combine. $row gives your output
$check = mysql_query("SELECT user_task_types, user_task_types_id FROM dotp_user_task_type WHERE user_id = '$user_id'");
while ($row = mysql_fetch_array($check) )
{
echo $row;
}

Formatting results from printing an array (PHP and MySQL)

I have the following code:
<?php
include('settings.php'); //Here I have my connection string
$result = mysql_query("SELECT myrow FROM mytable");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['myrow'];
}
print_r($storeArray);
?>
And the results look like this:
Array ( [0] => emailaddress1#email.com [1] => [2] => emailaddress2#email.com [3] => emailaddress3#email.com )
I was wondering what I need to do in order for it to print like this:
emailaddress1#email.com, emailaddress2#email.com, emailaddress3#email.com ..and so forth.
The reason is I've been tasked with creating mailing list, so I need to print out all of the email addresses in the database in an easy-to-insert into Outlook format
Is there a better way?
implode( ', ', $storeArray)
Or try this method :
foreach($storeArray as $value)
$stringval.= $value.', ';
$finalval = substr($stringval,0,-2);
echo $finalval;

Categories