Post Updated
I would like to create dynamic Array in PHP to provide the same output like static Array below, I have tried to do it with while statement but it doesn't work. Could you please provide me some tips?
I would like to use 2 values from MySQL and save them in to $to variable
so first send_to1 (user account) and then value1 (amount)
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM users");
$to=Array(
while($row = mysqli_fetch_array($result))
{
$send_to1 => $value1,
$send_to2=> $value2
}
);
mysqli_close($con);
?>
It's as simple as just adding elements to the array:
//Setup blank array
$example = array();
//Create a loop, for example purposes.
foreach(range(0, 99) as $i){
//Create random variable that we'll add to our array
$randVar = mt_rand(1, 90000);
//$i will be our array key/index
$example[$i] = randVar;
}
//var_dump the array so you can see the structure / end result
var_dump($example);
You could also create it like so:
//Create random array key/index
$myRandKey = mt_rand(1, 90000);
//Create random variable value.
$myRandVar = mt_rand(1, 90000);
//Setup an array
$example = array(
$myRandKey => $myRandVar
);
//Another array key that we'll add to our array
$secondKey = 'test';
//Add it
$example[$secondKey] = 'This is just an example!';
//Dump out the array
var_dump($example);
array_push will also work (using mysql_fetch_assoc, like in your example):
$example = array();
while($row = mysql_fetch_assoc($result)){
array_push($example, $row);
}
var_dump($example);
In your particular example (since you added your code):
print_r($new_array[] = $row[]);
should be changed to:
print_r($new_array[] = $row);
In your code, I'd change it to:
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[] = $row;
}
Or, if you want to key your array by a unique column (Primary key, for example):
$new_array = array();
while($row = mysqli_fetch_array($result)){
$new_array[$row['id']] = $row;
}
Look, this is so easy, you just need to pay more attention to the answers you're getting here.
Here is the simplest way you can do it:
$to = array();
$to[] = array($send_to1 => $value1);
$to[] = array($send_to2 => $value2);
while ( $row = mysqli_fetch_array($result) ) {
$to[] = array($row['send_tox' => $row['valuex']);
}
You need to first understand how Arrays and Loops work in PHP, then try to make a dynamic array in a loop.
Actually you almost got it. It's lower A in 'array'
To initialize an empty array:
$to = array();
In your case (you already have some values), you can do:
$to = array(
$send_to1 => $value1,
$send_to2=> $value2
);
In either case, you can later add more elements doing
$to[$someOtherKey] = $someOtherValue;
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"}]
I'm trying to create a single array of status id's and their names pulled from the database. My array needs to come out looking like this
$options = array("1" => "Active", "2" => "Inactive");
I've been trying to use array_push and array merge but it keeps going wrong. Here is what I have so far...
$allStatus = implode(',', array('1', '2'));
$statuses = $clCont->getAllRecords('*', '`status` WHERE idstatus IN ('.$allStatus.')');
$status = mysqli_fetch_assoc($statuses);
$statusOpt = array();
do
{
array_push($statusOpt[$status['idstatus']],$status['statusName']);
}
while ($status = mysqli_fetch_assoc($statuses));
$rows = mysqli_num_rows($statuses);
if($rows > 0)
{
mysqli_data_seek($statuses, 0);
$status = mysqli_fetch_assoc($statuses);
}
print_r($statusOpt);
Ok, let's try to modify your code:
$allStatus = implode(',', array('1', '2'));
$statuses = $clCont->getAllRecords('*', '`status` WHERE idstatus IN ('.$allStatus.')');
// you don't need to fetch first item.
// $status = mysqli_fetch_assoc($statuses);
// and use a do-while loop
// use just while:
$statusOpt = array();
while ($status = mysqli_fetch_assoc($statuses))
{
$id = $status['idstatus'];
// The first time you try to put a value in a
// $statusOpt[$status['idstatus']] it's not exists,
// so you should define it explicitly:
if (!isset($statusOpt[$id])) {
$statusOpt[$id] = array();
}
// after that it should be okay:
array_push($statusOpt[$id],$status['statusName']);
}
print_r($statusOpt);
while($info5 = mysql_fetch_array($result)){
$namelist[] = $info5["name"];
$idlist[] = $info5["id"]
}
I want an array which has the entries of the array idlist as it's index and entries of the array namelist as it's values.
Is there a short way to do this?
Like this, if I understand your request. Use $info['id'] as the array key to the accumulating array $namelist (or whatever you decide to call it)
while($info5 = mysql_fetch_array($result)){
$namelist[$info['id']] = $info5["name"];
}
i'm not sure i understand your question but probably something like this should be fine.
while($info5 = mysql_fetch_array($result)){
$values[$info5['id']] = $info5;
}
$result = array();
while($info5 = mysql_fetch_array($result))
{
$id = $info5['id'];
$name = $info5['name'];
$result[$id] = $name;
}
This should give the output array $result you want, if I understood correctly.
You can use array_combine as long as the arrays have the same number of values:
$result = false;
if (count($idlist) == count($namelist))
$result = array_combine($idlist, $namelist);
Check out the docs: http://www.php.net/manual/en/function.array-combine.php
But, I also wonder why you don't just do it in the while loop:
$values = array();
$namelist = array();
$idlist = array();
while($info5 = mysql_fetch_array($result)){
$namelist[] = $info5["name"];
$idlist[] = $info5["id"]
// this is the combined array you want?
$values[$info5["id"]] = $info5["name"];
}
how take string from array define as new array,
how to code in php
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "1";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
I want to take string from $column array define as new array.
how to code it?
or if my question is stupid , my please to have suggestion.
thank you.
Answer I made on your previous question:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $column_name => $column_value) {
$temp_array[$column_name][$i] = $column_value;
}
$i++;
}
foreach ($temp_array as $name => $answer) {
$$name = $answer;
}
}
I can't see why you'd want to model your data like this, you're asking for a world of hurt in terms of debugging. There are "variable variables" you could use to define this, or build global variables dynamically using $GLOBALS:
$somevar = "hello"
$$somevar[0] = "first index"; // creates $hello[0]
$GLOBALS[$somevar][0] = "first index"; // creates $hello[0] in global scope
try
$array = array();
foreach ($results as $r){
foreach ($column as $col ){
$array[$col][] = $r[$col];
}
}
extract ($array);
or you can simply do this
$id = array();
$name = array();
$value = array();
foreach ( $results as $r ){
$id[] = $r['id']; // or $r[0];
$name[] = $r['name'];
$value[] = $r['value'];
}
Hope this is what you asked
This is pretty dangerous, as it may overwrite variables you consider safe in your code. What you're looking for is extract:
$result = array();
while ($row = mysql_fetch_array($result))
foreach ($column as $i => $c)
$result[$c][] = $row[$i];
extract($result);
So, if $result was array( 'a' => array(1,2), 'b' => array(3,4)), the last line defines variables $a = array(1,2) and $b = array(3,4).
You cannot use variable variables right on for this, and you shouldn't anyway. But this is how you could do it:
foreach (mysql_fetch_something() as $row) {
foreach ($row as $key=>$value) {
$results[$key][] = $value;
}
}
extract($results);
Ideally you would skip the extract, and use $results['id'][1] etc. But if you only extract() the nested array in subfunctions, then the local variable scope pollution is acceptable.
There is no need for arrays or using $_GLOBALS, i believe the best way to create variables named based on another variable value is using curly brackets:
$variable_name="value";
${$variable_name}="3";
echo $value;
//Outputs 3
If you are more specific on what is the array you receive i can give a more complete solution, although i must warn you that i have never had to use such method and it's probably a sign of a bad idea.
If you want to learn more about this, here is a useful link:
http://www.reddit.com/r/programming/comments/dst56/today_i_learned_about_php_variable_variables/
I want to add an additional value into an array before passing it to json_encode function,
but I can't get the syntax right.
$result = db_query($query);
// $row is a database query result resource
while ($row = db_fetch_object($result)) {
$stack[] = $row;
// I am trying to 'inject' array element here
$stack[]['x'] = "test";
}
echo json_encode($stack);
If it's an array you can directly add a value:
$row['x'] = 'test';
$stack[] = $row;
if it's an object you can add another property:
$row->x = 'test';
$stack[] = $row;
if you want to keep the object and the extra value separated:
$data = array($row, 'x' => 'test');
$stack[] = $data;
but this does work.
$stack[] = $row;
$row->x = 'test';
How about something like:
$row['x'] = 'test';
$stack = $row;