php string name as variable in array - php

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/

Related

Add Object to Array while looping

One of my PDO statements returns an array. For JSON encoding I want to cast this array to an Object and append it to another array.
while($row = $sth->fetch()){
foreach($row as $key=>$value){
$r = (object) $row;
$recordArray[] = $r;
}
}
$json->record = $recordArray;
echo json_encode($json);
$recordArray seems to stay empty but it doesn't if I write $recordArray[] = "test" in the loop. So there must be something wrong with my Object $r but I can't spot the mistake. Any help is appreciated.
Here is an easier way
echo json_encode(array('record'=>$sth->fetchAll(PDO::FETCH_OBJ)));
Your foreach is wrong: in body you use object on which you iterate.
May be you mean this?
$records = [];
while($row = $sth->fetch()) {
$current = [];
foreach($row as $key => $value) {
$current[$key] = $value;
}
$records[] = $current;
}
If I understood, you want to loop over $row and add every object within $row to $recordArray.
Then you should do this:
while($row = $sth->fetch()){
foreach($row as $value){
$recordArray[] = $value;
}
}

What is the problem with this foreach loop?

why doesnt this array work? What do I do wrong? The result of my foreach loop is always either empty or just some weird numbers and signs. So what is wrong with my foreach loop?
$array = array();
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array["some"] = $row["some"];
$array["some2"] = $row["some2"];
}
}
foreach($array as $property=>$value) {
echo '<p>'.$value["some"].' - '.$value["some2"].'</p>'; }
$array will have only two properties, some and some2. Therefore your foreach loop doesn't make any sense. The foreach will loop two times, the first time with this:
$property = 'some';
$value = $row["some"];
and the second with this:
$property = 'some2';
$value = $row["some2"];
You will have to make $array multidimensional in your first loop by doing this:
while($row = mysqli_fetch_array($result)) {
$new = array();
if(!empty($row["some"])) {
$new["some"] = $row["some"];
$new["some2"] = $row["some2"];
$array[] = $new;
}
}
or shorter:
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array[] = array('some' => $row["some"],
'some2' => $row["some2"]);
}
}
$array["some"] and $array["some2"] are specific array elements. You are overwriting them every iteration of your while loop.
Not sure what you're trying to actually accomplish but I think possibly this is what you want:
$array = array();
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array["some"][] = $row["some"];
$array["some2"][] = $row["some2"];
}
}
foreach($array["some"] as $property=>$value) {
echo '<p>'.$value.' - '.$array["some2"][$property].'</p>';
}
or
$array = array();
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array[] = array('some' => $row["some"],
'some2' => $row["some2"]);
}
}
foreach($array as $property=>$value) {
echo '<p>'.$value['some'].' - '.$value['some2'].'</p>';
}
or similar...kinda depends on what you're ultimately trying to accomplish...
This doesn't explain the weird numbers and signs, but you are overwriting $array['some'] and $array['some2'] on each loop iteration.
Instead, try this:
while($row = mysqli_fetch_array($result)) {
if(!empty($row["some"])) {
$array[] = array("some"=>$row['some'], "some2"=>$row['some2']);
}
}
$array[] = array('some' => $row["some"], 'some2' => $row["some2"]);
But it would be better to retrieve only these columns.
Emil has the right answer :D. I love how people post so fast on here lol.

php loop statement question

I'm wondering if it is possible to loop a variable within a variable? Here is something I want to setup:
$var1 = Benjamin
$var2 = George
$var3 = Abraham
and probably echo out something like
<li>Benjamin</li>
<li>George</li>
<li>Abraham</li>
but I want to know, if I want to add $var4 = ..., $var5 = ..., is there a way I can do this all in a loop? I'm thinking having an empty() function that'll loop the variable names/numbers until reaches the first empty variable?
You could store them in an array.
$names = array('Mike', 'Jim', 'Tom', 'Stacy');
foreach($names as $name){
echo $name;
}
As seen here: http://www.ideone.com/f7Ce7
In PHP you can do this:
$var1 = "foo";
$var2 = "bar";
$name = "var1";
$i=1;
while( !is_null( $$name ) ) {
echo '<li>' . $$name . '</li>';
$i++;
$name = "var$i";
}
but a better solution may be using an array and a foreach
This sounds like you want to use arrays and foreach. Am I missing something?
$presidents = array(
'Benjamin', 'George', 'Abraham'
);
foreach($presidents as $pres) {
echo "$pres\n";
}
$var=array('Benjamin', 'George', 'Abraham');
foreach ($var as $name){
echo $name;
}
A better solution would be arrays.
define it as:
$names = array(0=>"Benjamin",1=>"George",2=>"Abraham");
Then loop through it with:
foreach ($names as $id=>$name)
{
echo $name;
}
Then reference a name with $names[0], if you want to add another use $names[] = 'William';
Look up more information at:http://php.net/manual/en/language.types.array.php
This solution doesn't require the use of an array.
$var1 = 'Benjamin';
$var2 = 'George';
$var3 = 'Abraham';
//add as many variables as you want
$i = 0;
$currentVariable = 'var'.$i;
while (isset($$currentVariable)) {
//process variable
echo $$currentVariable;
$i++;
}

php string name as variable

$string = "id";
want result to be like
$id = "new value";
How do I code this in php?
Edit..
How about the below?
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "3";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
Theres 2 main methods
The first is the double $ (Variable Variable) like so
$var = "hello";
$$var = "world";
echo $hello; //world
//You can even add more Dollar Signs
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";
$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a
$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World
//... and so on ...//
#source
And the second method is to use the {} lik so
$var = "hello";
${$var} = "world";
echo $hello;
You can also do:
${"this is a test"} = "works";
echo ${"this is a test"}; //Works
I had a play about with this on streamline objects a few weeks back and got some interesting results
$Database->Select->{"user id"}->From->Users->Where->User_id($id)->And->{"something > 23"};
You are looking for Variable Variables
$$string = "new value";
will let you call
echo $id; // new value
Later in your script
Second answer in response to your edit:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
$id = array();
$name = array();
$value = array();
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
$id[$i] = $row['id'];
$name[$i] = $row['name'];
$value[$i] = $row['value'];
$i++;
}
}
This loops around your result, using the counter $i as the key for your result arrays.
EDIT
Additional answer in response to your comment:
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;
}
This code creates a temporary multidimensional array to hold the column names and values the loops around that array to create your variable variable arrays. As a side not I had to use the temp array as $$column_name[$i] doesn't work, I would love to see alternative answers to this problem.
Final note #Paisal, I see you have never accepted an answer, I wouldn't have put this much effort in if I had seen that before!
You can do this
$$string = "new value";
juste double $
Are you referring to variable variables?
That would accomplish something like this:
$string = "id";
$$string = "new value";
This produces a variable $id with the value "new value".
Don't do that. Just use an array.
$arr[$string] = 'new value';
ref: How do I build a dynamic variable with PHP?
Try this :
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$i = 0;
if ($num_rows) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row AS $key => $value) {
${$key}[$i] = $value;
}
$i++;
}
}
For those of us who need things explained in great detail...
// Creates a variable named '$String_Variable' and fills it with the string value 'id'
$String_Variable = 'id';
// Converts the string contents of '$String_Variable', which is 'id',
// to the variable '$id', and fills it with the string 'TEST'
$$String_Variable = 'TEST';
// Outputs: TEST
echo $id;
// Now you have created a variable named '$id' from the string of '$String_Variable'
// Essentially: $id = 'Test';

How can I easily remove the last comma from an array?

Let's say I have this:
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}
echoes "john-doe,foe-bar,oh-yeah,"
How do I get rid of the last comma?
Alternatively you can use the rtrim function as:
$result = '';
foreach($array as $i=>$k) {
$result .= $i.'-'.$k.',';
}
$result = rtrim($result,',');
echo $result;
I dislike all previous recipes.
Php is not C and has higher-level ways to deal with this particular problem.
I will begin from the point where you have an array like this:
$array = array('john-doe', 'foe-bar', 'oh-yeah');
You can build such an array from the initial one using a loop or array_map() function. Note that I'm using single-quoted strings. This is a micro-optimization if you don't have variable names that need to be substituted.
Now you need to generate a CSV string from this array, it can be done like this:
echo implode(',', $array);
One method is by using substr
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = "";
foreach($array as $i=>$k)
{
$output .= $i.'-'.$k.',';
}
$output = substr($output, 0, -1);
echo $output;
Another method would be using implode
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = array();
foreach($array as $i=>$k)
{
$output[] = $i.'-'.$k;
}
echo implode(',', $output);
I don't like this idea of using substr at all, since it's the style of bad programming. The idea is to concatenate all elements and to separate them by special "separating" phrases. The idea to call the substring for that is like to use a laser to shoot the birds.
In the project I am currently dealing with, we try to get rid of bad habits in coding. And this sample is considered one of them. We force programmers to write this code like this:
$first = true;
$result = "";
foreach ($array as $i => $k) {
if (!$first) $result .= ",";
$first = false;
$result .= $i.'-'.$k;
}
echo $result;
The purpose of this code is much clearer, than the one that uses substr. Or you can simply use implode function (our project is in Java, so we had to design our own function for concatenating strings that way). You should use substr function only when you have a real need for that. Here this should be avoided, since it's a sign of bad programming style.
I always use this method:
$result = '';
foreach($array as $i=>$k) {
if(strlen($result) > 0) {
$result .= ","
}
$result .= $i.'-'.$k;
}
echo $result;
try this code after foreach condition then echo $result1
$result1=substr($i, 0, -1);
Assuming the array is an index, this is working for me. I loop $i and test $i against the $key. When the key ends, the commas do not print. Notice the IF has two values to make sure the first value does not have a comma at the very beginning.
foreach($array as $key => $value)
{
$w = $key;
//echo "<br>w: ".$w."<br>";// test text
//echo "x: ".$x."<br>";// test text
if($w == $x && $w != 0 )
{
echo ", ";
}
echo $value;
$x++;
}
this would do:
rtrim ($string, ',')
see this example you can easily understand
$name = ["sumon","karim","akash"];
foreach($name as $key =>$value){
echo $value;
if($key<count($name){
echo ",";
}
}
I have removed comma from last value of aray by using last key of array. Hope this will give you idea.
$last_key = end(array_keys($myArray));
foreach ($myArray as $key => $value ) {
$product_cateogry_details="SELECT * FROM `product_cateogry` WHERE `admin_id`='$admin_id' AND `id` = '$value'";
$product_cateogry_details_query=mysqli_query($con,$product_cateogry_details);
$detail=mysqli_fetch_array($product_cateogry_details_query);
if ($last_key == $key) {
echo $detail['product_cateogry'];
}else{
echo $detail['product_cateogry']." , ";
}
}
$foods = [
'vegetables' => 'brinjal',
'fruits' => 'orange',
'drinks' => 'water'
];
$separateKeys = array_keys($foods);
$countedKeys = count($separateKeys);
for ($i = 0; $i < $countedKeys; $i++) {
if ($i == $countedKeys - 1) {
echo $foods[$separateKeys[$i]] . "";
} else {
echo $foods[$separateKeys[$i]] . ", \n";
}
}
Here $foods is my sample associative array.
I separated the keys of the array to count the keys.
Then by a for loop, I have printed the comma if it is not the last element and removed the comma if it is the last element by $countedKeys-1.

Categories