I have a multidimensional array, and I can not update one of these:
public function get_list($query){
if(mysql_query($query,DB::connect())){
$result = mysql_query($query);
if (mysql_affected_rows() != 0) {
while ($row = mysql_fetch_array($result)) {
$list_annunci[] = array(
"id" => $row["id"],
"title" => $row["title"]
);
if(mysql_query($immagini,DB::connect())){
$result_img = mysql_query($immagini);
if (mysql_affected_rows() != 0) {
while ($row_img = mysql_fetch_array($result_img)) {
$list_annunci[] = array(
"img" => $row_img["path_img"]
);
}
}
}
}
how do I insert the record in the array already declared?
tnx stefania
Use your ids as keys for the original array.
$list_annunci[$id] = array(
Make the database query returns those ids as well.
SELECT id, path_img
Then you can inject or update the right group.
$list_annunci[ $id ]["img"] = $row_img["path_img"];
^
|
from $row_img["id"]
Related
I've just achieved a code where I make an array with foreach and in the same code I already have an existing array. What I want to do is to make only one array with those two results. Here is my code for the first array :
$sql = "SELECT photoprofile,username from photo WHERE username IN ('somearray')";
$resol = array();
$resulol = mysqli_query($con,$sql);
$photos = mysqli_fetch_all($resulol, MYSQLI_ASSOC);
$photos = array_column($photos, "photoprofile", "username");
foreach ( $restest as $user ) {
if ( isset($photos[$user])) {
$res[] = $photos[$user];
}
else {
$res[] = '';
};
}
And here is my second array :
while($row = mysqli_fetch_array($result)){
array_push($res2, array(
"name"=>$row['name'],
"publisher"=>$row['username'],
"image"=>$row['photo'],
)
);}
If you have any tips, any comment or even a question (if I wasn't clear enough for you), just ask me ! Thanks !
Edit :
What I want to make is an array of this type :
[{"name":"usera","publisher":"Jeana","image":"urla",""photouser","url2a"},{"name":"userb","publisher":"Jeanb","image":"urlb","photouser","url2b"}]
You need to use the key you have in the first portion:
$sql = "SELECT photoprofile,username from photo WHERE username IN ('somearray')";
$resol = array();
$resulol = mysqli_query($con,$sql);
$photos = mysqli_fetch_all($resulol, MYSQLI_ASSOC);
$photos = array_column($photos, "photoprofile", "username");
# Set the username--vvvevvvvv
foreach($restest as $username => $user) {
# Store the username as the key here for reference later
$res[$username] = (isset($photos[$user]))? $photos[$user] : '';
}
In this array, reference the username from the other array:
while($row = mysqli_fetch_array($result)){
$res2[] = array(
"name"=>$row['name'],
"publisher"=>$row['username'],
"image"=>$row['photo'],
# Using the username as the key name, see if it $res has a saved value
"photouser" => (isset($res[$row['username']]))? $res[$row['username']] : false
);
}
I finally achieve what I wanted to do, by using a replacement technic :
With the foreach loop, I've created an array with the parameter profilepic, on the other array, I've created another parameter with a default value, then I replaced it.
My code : First my foreach loop :
foreach ( $restest as $user ) {
if ( isset($photos[$user])) {
array_push($res1, array(
"profilepic"=>$photos[$user]));
}
else {
array_push($res1, array(
"profilepic"=>'defaultvalue'));;
};
}
and then I changed :
while($row = mysqli_fetch_array($result)){
array_push($res2, array(
"name"=>$row['name'],
"publisher"=>$row['username'],
"image"=>$row['photo'],
"profilepic"=>'defaultvalue'
)
);}
And finally I replaced it by :
$res = array_replace_recursive($res2,$res1);
So my final array with echo json_encode($res) is:
[{"name":"usera","publisher":"Jeana","image":"urla",""profilepic","url2a"},{"name":"userb","publisher":"Jeanb","image":"urlb","profilepic","defaultvalue"}]
function practise()
{
$this->load->database();
$qry = mysql_query("select * from demmo");
if (mysql_num_rows($qry) > 0)
{
while ($row = mysql_fetch_array($qry))
{
$created = $row['created'];
//from here
$qry = mysql_query("select * from demmo where created = '$created'");
while ($res = mysql_fetch_array($qry))
{
$user_id = $res['id'];
$name = $res['name'];
$created2 = $res['created'];
$users[] = array('user_id' => $user_id, 'name' => $name);
}
$dotts[] = array('created' => $created2);
//till here
}
return array ($dotts,$users);
}
}
in demmo table i am trying to fetch data and showing that data according to date .the problem is that the code is only selecting one date from the table from created rows and showing that data only .fortunately data shown is not only last but the data with actual date.
You need to create an array and use array_push to get more than one result. Right now your code is only returning the last result of the while loop:
For example, to get all of the dates:
$dotts = array();
$allusers = array();
while ($res = mysql_fetch_array($qry))
{
$user_id = $res['id'];
$name = $res['name'];
$created2 = $res['created'];
array_push($dotts, $created2);
$users[] = array('user_id' => $user_id, 'name' => $name);
array_push($allusers, $users);
}
//
return array ($dotts,$allusers);
You need to create an array and use array_push function , then only it will have more than one value.
example:
create an empty array as
$allUser = array();
then after this line
$users[] = array('user_id' => $user_id, 'name' => $name);
use array_push as
array_push($allUser, $users);
}
return array($dots, $allUser);
I can't seem to get the array to return from the function correctly, every time I run the script it just echoes out 0, even though I have checked that the MySQL query returned at least 1 row. I've also tried using $_GLOBALS["FORUM_ANSWERS"][] = ..., however it still did not work.
public function getAnswers() {
$dbh = $this->dbh;
$id = $this->question_id;
$q = $dbh->prepare("SELECT * FROM answers WHERE question_id = :id");
$q->bindParam(":id", $id);
$q->execute();
$nr = $q->rowCount();
if ($nr == 0) {
echo "No Questions";
}
$_GLOBALS["FORUM_ANSWERS"] = [];
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
array_push($_GLOBALS["FORUM_ANSWERS"], array(
"num_id" => $row["num_id"],
"question_id" => $row["question_id"],
"answer" => $row["answer"],
"name" => $row["name"],
"username" => $row["username"],
"ip" => $row["ip"],
"date" => $row["date"],
));
}
return $GLOBALS["FORUM_ANSWERS"];
}
SEPERATE FILE:
$answers = $forum->getAnswers();
echo count($answers);
You are assigning to $_GLOBALS and returning $GLOBAL.
You actually don't need to use a global array by the look of it - I would just assign the array to a variable (that you initialise in the function) and return that.
I'm trying to get the values from a Query String and add them to an array inside of an array. The output Query String is something like:
add_to_cart.php?product_id=4&product_name=Pizza&quantity=1&additional_id[]=1&additional_quantity[]=3&additional_id[]=4&additional_quantity[]=5
I'm getting each additional_id and additional_quantity variables presents in the Query String with the code below. I compare each of the additional_id with the IDs that I have in database table additionals and insert all into an array. The following code exists in my file add_to_cart.php file:
if(isset($_SESSION['cart']))
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns = array
(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price,
'quantity' => $quantity,
'additionals' => array()
);
if(isset($_GET['additional_id']) && $_GET['additional_id'] != "")
{
foreach($_GET['additional_id'] as $additional => $value)
{
$additional_id = $value;
if(isset($_GET['additional_quantity'][$additional]))
{
$additional_quantity = $_GET['additional_quantity'][$additional];
if($additional_quantity <= 0 || $additional_quantity > 5)
{
$additional_quantity = null;
}
else
{
$sql2 = "SELECT additional_id, additional_name, additional_price FROM additionals WHERE additional_id LIKE '{$additional_id}'";
$stmt2 = $connection->prepare($sql2);
$stmt2->execute();
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns['additionals'][]['additional_id'] = $additional_id;
$columns['additionals'][]['additional_name'] = $additional_name;
$columns['additionals'][]['additional_price'] = $additional_price;
$columns['additionals'][]['additional_quantity'] = $additional_quantity;
}
}
}
}
}
$_SESSION['cart'][$product_id_session] = $columns;
}
header('Location: products.php?action=added&product_name=' . $product_name);
}
Once everything is added in the cart SESSION, in the cart.php page I'm trying to show the products with their selected additionals and quantities with:
foreach($_SESSION['cart'] as $product)
{
echo "<tr>";
echo "<td>{$product['product_name']}</td>";
echo "<td>${$product['product_price']}</td>";
echo "<td>{$product['quantity']}</td>";
echo "<td>";
foreach($product['additionals'] as $additional)
{
echo "<p>{$additional['additional_quantity']}x{$additional['additional_name']} - {$additional['additional_price']}</p>";
}
echo "</td>";
echo "</tr>";
}
But I'm doing something wrong, I think these two codes are not working properly.
My output is embarrassed, something like this:
Am I doing it by the right way? Maybe I'm not looping right with foreach, or the additionals are not being added with success? Sorry for the mistakes, I never worked with multidimensional arrays before. Is there a way to do what I am intending to? Thanks!
solution as per the comments-
Your issue is caused by $columns['additionals'][] as it is causing each value to being added as its own array. This is solved by added $additional as the array key -
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns['additionals'][$additional]['additional_id'] = $additional_id;
$columns['additionals'][$additional]['additional_name'] = $additional_name;
$columns['additionals'][$additional]['additional_price'] = $additional_price;
$columns['additionals'][$additional]['additional_quantity'] = $additional_quantity;
}
or you could also do-
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns['additionals'][] = array('additional_id' => $additional_id,
'additional_name' => $additional_name,
'additional_price' => $additional_price,
'additional_quantity' => $additional_quantity);
}
I have a table
Which I want show recursively like below picture
I am using a recursive function in php
function reccall($cat_id)
{
global $no,$recArray;
$sql = "SELECT a.*
FROM cat_master
WHERE
parent_id = $cat_id
ORDER BY
id ASC
";
$result = mysql_query($sql) or die("Could not fetech Recursively");
while($row = mysql_fetch_object($result))
{
$recArray[$no]['value'] = mysql_real_escape_string($row->value);
$recArray[$no]['id'] = $row->id;
++$no;
reccall($row->id);
}
return $recArray;
}
but I am not able to generate a structured array like how the order is not the picture. A simple array is created all the time. Can anyone help me with creating the structured array like the order shown above.
<?
// I identified this function separately because it is performed only once, for preparing data
// It's collect an array of all parents in the correct order for each id
function dest($array) {
foreach($array as $key=>$value) {
if($value['pid']==0) continue;
$pid = $key;
$array[$key]['dest'] = array();
while ( $pid = $array[$pid]['pid'] ) {
if($key == $pid) exit("this tree is broken");
$array[$key]['dest'][] = $pid;
}
}
return $array;
}
// Recursive function that puts the items in the correct tree. removes the parameter dest.
function tree($array) {
foreach($array as $key=>$value) {
if( is_array($value['dest']) && !empty($value['dest']) ) {
$pid = array_pop($value['dest']);
if( empty($value['dest']) ) unset($value['dest']);
$array[$pid]['childrens'][$key] = $value;
$array[$pid]['childrens'] = tree($array[$pid]['childrens']);
unset($array[$key]);
}
}
return $array;
}
$array = array(
1 => array(
'title'=>'q',
'pid'=>0,
),
2 => array(
'title'=>'w',
'pid'=>1,
),
3 => array(
'title'=>'e',
'pid'=>0,
),
4 => array(
'title'=>'r',
'pid'=>2,
),
5 => array(
'title'=>'t',
'pid'=>1,
),
);
$tree = tree( dest($array) );
echo '<pre>';
print_r($array);
print_r($tree);
?>
By the way, I should note that these arrays are not very useful. Better to use the result of the function dest().
use this function instead of your function and your problem will be solved I hope
function reccall($cat_id)
{
$sql = "SELECT a.*
FROM cat_master
WHERE
parent_id = $cat_id
ORDER BY
id ASC
";
$result = mysql_query($sql) or die("Could not fetech Recursively");
while($row = mysql_fetch_object($result))
{
$recArray[$no]['main']['value'] = mysql_real_escape_string($row->value);
$recArray[$no]['main']['id'] = $row->id;
$recArray[$no]['child'] = reccall($row->id);
++$no;
}
return $recArray;
}