I've had a look through searches but there are so many differently worded question that I'm not sure which I should be looking for. Nor can I think how to word this to the best of my ability, but here goes:
I would like to take a mysqli_fetch_assoc() result and create an array for each row.
Let's say the result had two rows:
[0][0] = Cheese
[0][1] = 1
[1][0] = Milk
[1][1] = 2
How can I drop those into a newly created array let's say called $items?
What I'm hoping to achieve is:
$items = array(
array("Cheese",1),
array("Milk", 2)
);
The only code I have so far is this:
if($row = mysqli_fetch_assoc($q)) {
for($i=0;$i<$total;$i++) {
$items[$i][] = $row[$i];
}
}
I have not tried this, but I have this very unsettling feeling that it definitely won't be working.
would this not do it?
if($row = mysqli_fetch_assoc($q)) {
foreach($row as $r) {
$items[] = $r;
}
}
$new_arr = array();
while ($row = mysql_fetch_assoc($q))
{
foreach($row as $value){
$new_arr[][$value[0]] = $value[1];
}
}
I think this is what you need
while ($row = mysql_fetch_assoc($q))
{
$arr = [];
foreach ($row as $value)
$arr[] = $value;
$items[] = $arr;
}
var_dump($items);
mysqli_result::fetch_all()
"Returns an array of associative or numeric arrays holding result rows"
I think you're thinking too hard. A two dimensional array is already an array containing arrays. In your case, the result of fetch_all is precisely an array containing 'an array for each row'
If you're not intending to store the whole result set then you can do:
$rows[] = Array();
while ($row = mysqli_fetch_row() && $someCondition) $rows[] = $row;
but really you'd be better off to put a LIMIT on the query if possible.
Related
I have 4 arrays, each one holds another column of a table, I would like to create one array with the data ordered per array[$i]. All arrays have the same number of values: $namesArr, $folderArr, $updatedAt, $valuesArr .
I would like my new array to be contain:
$namesArr[0], $folderArr[0], $updatedAt[0], $valuesArr[0],
$namesArr[1], $folderArr[1], $updatedAt[1], $valuesArr[1],
$namesArr[2], $folderArr[2], $updatedAt[2], $valuesArr[2],
...
I guess the solution is pretty simple, but I got stuck :(
Can anyone help?
I would do something like:
$arr = array_map(function () { return func_get_args(); },$namesArr, $folderArr, $updatedAt, $valuesArr);
You can use foreach loop to merge 4 arrays:
foreach ($namesArr as $key => $value) {
$arr[$key][] = $value;
$arr[$key][] = $folderArr[$key];
$arr[$key][] = $updatedAt[$key];
$arr[$key][] = $valuesArr[$key];
}
Thus $arr will be the merged array
<?php
$newArr = array();
for ($i = 0; $i < count($namesArr); $i++)
{
$newArr[$i][0] = $namesArr[$i];
$newArr[$i][1] = $folderArr[$i];
$newArr[$i][2] = $updatedAt[$i];
$newArr[$i][3] = $valuesArr[$i];
}
?>
Explanation
What this will do is iterate depending on how many elements there are in $namesArr.
I utilised a multidimensional array here so that the first set of square brackets is effectively the "row" in a table, and the second set of square brackets are the "column" of a table.
do the following way:
while($db->query($sql)){
$namesArr[] =$db->f('names');
$folderArr[]=$db->f('folder');
$updatedAt[]=$db->f('updated');
$valuesArr[]=$db->f('values');
}
I have simple PHP array with data from checkbox. I need add values into array and then insert data into database. It works but foreach not infringement parameter.
So i testing with increment:
$arr = array();
array_push($arr, $_POST['chbox']);
and it looks like 123,125 in array (two elements)
Next step is to return number of elements (or values in next step):
$id=0;
foreach( $arr as $row)
{
$id++;
};
and returns $id=1;
if i'm trying read values:
foreach( $arr as $row)
{
$row[$id]
$id++;
};
Return only 123
If you are doing a foreach, $row is the value already.
foreach($arr as $row) {
echo $row;
$id++;
}
In your foreach() loop, $row is just one array value. Not the array. Replace with $arr should solve.
$id = 0;
foreach( $arr as $row ){
echo $arr[$id];
$id++;
}
echo 'Total items: ' . $id; // OR count( $arr );
$arr =array(123,125);
foreach($arr as $arrr):
echo $arrr.',';
endforeach;
Output will be:
123,125,
Just try following
foreach($arr as $row){
echo $row;
};
Edit 1:
Better use var_dump($_POST["chkbox"]) or print_r($_POST["chkbox"]) to see the array you are getting. Then it will be easier for you to decide how to get data.
I'm trying to put an array into a query but I doens't work. I'm tying it with implode() but then it gives me " Array to string conversion in ... on line 26". Why? With json_encode it worked out ...
Thanks for your help!
$sql = mysql_query("SELECT follows
FROM follow
WHERE follower LIKE '".$id."'") or die (mysql_error());
if(mysql_num_rows($sql) < 1){
echo "<br/>";
echo "Follow someone";
} else {
//Put all the id's of the users the user is following in an array.
$i = 0;
$user_follows = array();
while ( $row = mysql_fetch_assoc($sql) )
{
$user_follows[$i] = $row;
$i++;
}
$user_follows = implode(" , ", $user_follows);
echo $user_follows;
}
The second argument to implode must be an array of strings. But you're doing:
$user_follows[$i] = $row;
Since $row is an array, you're making an array of arrays (a 2-dimensional array), not an array of strings. That should be:
$user_follows[] = $row['follows'];
You don't need the $i variable, assigning to $array[] appends a new element to the array.
I have the following.
while($row = mysql_fetch_array($result))
{
$item = "itemCount_".$row['id'];
if ($_POST[$item] > 0)
{
$items2 = array( $i=> array($row['item'],$row['price']));
$i++;
echo $item." = ".$_POST[$item]." ".$i."<br>";
}
}
I would have thought that this would put each item in a array but it only puts the last item in the loop in. where is my fundamental flaw?
$items2 = array( $i=> array($row['item'],$row['price']));
That just keeps reassigning $items2 to a new array. Don't even worry about the $i counter and use
$items2[] = array($row['item'], $row['price']);
PHP Arrays
You're initializing a new array every time you go through the loop, it's better to use the array_push() function.
I am wondering how I can add a string variable to the current array. For example, I have an array called $finalarray. Then I have a loop that adds a value on every run. Basically:
$finalarray = $results_array + string;
A very basic structure. I am using this for MySQL so that I can retrieve the final array of the column.
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray = $finalarray + $results_array["column"];
}
Edit:
Currently using this code (still not working):
$query = “SELECT * FROM table”;
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["name"];
}
echo $finalarray;
The problem is that it just says "Array"
Thanks,
Kevin
Answer to your edited question:
You cannot use just a single echo to print the entire array contents. Instead
Use
var_dump($finalarray);
or
print_r($finalarray);
to print the array contents..
Use the [] notation. + is for unioning two arrays.
$array = array('foo');
$array[] = 'bar'.
// $array == array('foo', 'bar')
You can use the function array_push or [] notation:
array_push($array, 'hi');
$array[] = 'hi';
Take a look at this
$query = "SELECT * FROM table";
$showresult = mysql_query($query);
while($results_array = mysql_fetch_assoc($showresult))
{
$finalarray[] = $results_array["column"];
}
// Add X to the end of the array
$finalarray[] = "X";
Codaddict is correct. You are looking to output the last element that was added to the array.
echo end($final_array);
That will move the array's pointer to the last element added to it and then output it. Since you're adding the elements to the array in this manner...
$finalarray[] = $results_array["name"];
The key for each of your elements will be sequential, 0,1,2,3...so on and so forth. Another less elegant solution to get the last element would be...
echo $final_array[count($final_array) - 1];
echo implode($finalarray);
Or with a custom join "glue"
echo implode(', ', $finalarray);