Fetch array and feed it to a variable inside a loop - php

In the following code I simple feed the values of the form
$t = $_GET['type'];
$p = $_GET['product'];
$b = $_GET['brand'];
$c = $_GET['category'];
$attribute = getattributes($p,$b,$c);
$count = count($attribute);
$i=0;
The variable $attribute has
Array([0]=>size [1]=>weight)
Now using the above array i want to generate the following lines
$size = $_GET['size'];
$weight = $_GET['weight'];
I don't want to assign manually just like the above but create the two lines using loops.
Something like
$i=0;
while($i < $count)
{
'$'.$attribute[$i] = '$_GET['.$attribute[$i].']'; //edited part
}
I don't know if this will work, could somebody provide a simple piece of code to achieve the same?
Solution Code:
Awlad Liton: Thank for your answer. There is a minor change in your code which gave the desired output (value form the form)
foreach($attribute as $k => $v){
$$v = $_GET[$v];
}

Try this:
Demo: https://eval.in/96388
$attribute = array(0=>'size', 1=>'weight');
foreach($attribute as $k => $v){
$$v = '$_GET['."'$v'".']';
}
echo $size." ";
echo $weight;
OUTPUT:
$_GET['size'] $_GET['weight']
UPDATE:
as you reply you can do this:
foreach($attribute as $k => $v){
$$v = $_GET[$v];
}

you are almost right. try this:
$$attribute[$i] = $_GET[$attribute[$i]];
http://php.net/manual/en/language.variables.variable.php

Related

How to use a foreach loop o an array for searching?

I have my source code here:
$title = "news1";
$a = array();
foreach($page_news as $keys=>$news) // this comes from controller including news1.
{
$x[] = $news->title;
$x[] .= $news->url;
}
// I want to get the index of matches where $x[values = "news1"]
$key_title = array_search($title,$a);
Then my question is : if I get the index of news->title, how can I get the correspondent index of $news->url?
As you always add the url after the title, you could simply add one to the index of your title to get the index of the url.
$title = "news1";
$a = array();
foreach($page_news as $keys=>$news) {
$x[] = $news->title;
$x[] = $news->url;
}
$key_title = array_search($title, $a);
$key_url = $key_title + 1;
A better way would be to use a multi dimensional array and use the title as the key - in this way, you don't need array_search
$a = array();
foreach($page_news as $keys=>$news) {
$x[$news->title] = [
'title' => $news->title,
'url' => $news->url
];
}
$entry = $a[$title];
echo $entry['title'];
echo $entry['url'];
Here is some idea to achieve it :
1/ Create an associative array for each title + url :
$title = "news1";
$a = array();
foreach($page_news as $keys = >$news)
{
$a[] = array(
'title' => $news->title,
'url' => $news->url
}
Then to find the key of $title :
foreach ($a as $key => $data) {
if ($data['title'] == $title) {
$key_title = $key;
}
}
Then echo $key_title will give you the key.
If you want to avoid the foreach loop, I recommand you to do what Phillip suggest : add the title as key.
2/ If you know the title you want to search before the first foreach loop (in your example you have the title before), maybe you can get it in this loop :
$title = "news1";
$a = array();
$key = 0;
foreach($page_news as $keys => $news)
{
$a[$key] = $news->title;
if ($news->title == $title) {
$key_title = $key;
}
$key++;
$a[$key] = $news->url;
$key++;
}
Then echo $key_title will give you the key and echo $key_title + 1 will give the key of the associated url.
3/ And third idea is to do what the anwser if Philipp suggest with :
$key_title = array_search($title, $a);
$key_url = $key_title + 1;
If your using PHP 7+, you can use array_column to convert the data into an indexed list of objects...
$indexed = array_column($page_news, null, "title");
echo "url=".$indexed[$title]->url;
BUT if you don't need this data for anything else, you would be better off doing a simple foreach and compare it against each item. This saves converting and storing all of the data which isn't used later ...
$url = "";
foreach ( $page_news as $news ) {
if ( $news->title = $title ) {
$url = $news->url;
break;
}
}
echo "url=".$url.PHP_EOL;
(this works in most versions of PHP)

php dictionary-style array and sort by specific key name

I have a foreach construct:
foreach($_POST as $name => $value) {
if($value && $value > 0){ // ensure we have a positive amount
$composite = explode("-", Replace($name, "ScheduleID_", ""));
$scheduleID = $composite[0];
$thisUserID = $composite[1];
$payPalEmail = $composite[2];
$amount = $value;
$counter++;
$sum += $value;
}
}
I'm getting correct values in all my variables. Inside the foreach I need to construct an array containing these 4 values:
$scheduleID
$thisUserID
$payPalEmail
$amount
...and then sort the array by $thisUserID. And then I need to know how to build the foreach to correctly iterate the new array and grab each of my values.
IMPORTANT: Every $scheduleID will be unique, but the other 3 values will sometimes repeat.
I was thinking something like this, but can't get it to work right:
$object["ScheduleID"] = $scheduleID
$object["UserID"] = $thisUserID
$object["PayPalEmail"] = $payPalEmail
$object["Amount"] = $amount
(and then perform the sort on $object["UserID"]) - I have tried different sort schemes from stackoverflow and php docs, but I must be doing something wrong.
Thanks in advance.
You can just prepare array in foreach like this:
foreach($_POST as $name => $value) {
if($value && $value > 0){ // ensure we have a positive amount
$composite = explode("-", Replace($name, "ScheduleID_", ""));
$objects[$composite[0]] = array(
'UserID' => $composite[1],
'payPalEmail' => $composite[2]
);
$amount = $value;
$counter++;
$sum += $value;
}
}
ksort($objects);
Then after foreach You can sort array by ksort.

loop through an array and show results

i m trying to do a loop but get stacked ,
i have a function that convert facebook id to facebook name , by the facebook api. name is getName().
on the other hand i have an arra with ids . name is $receivers.
the count of the total receivers $totalreceivers .
i want to show names of receivers according to the ids stored in the array.
i tried every thing but couldnt get it. any help will be appreciated . thanks in advance.
here is my code :
for ($i = 0; $i < $totalreceivers; $i++) {
foreach ( $receivers as $value)
{
echo getName($receivers[$i]) ;
}
}
the function :
function getName($me)
{
$facebookUrl = "https://graph.facebook.com/".$me;
$str = file_get_contents($facebookUrl);
$result = json_decode($str);
return $result->name;
}
The inner foreach loop seems to be entirely redundant. Try something like:
$names = array();
for ($i = 0; $i < $totalReceivers; $i++) {
$names[] = getName($receivers[$i]);
}
Doing a print_r($names) afterwards should show you the results of the loop, assuming your getNames function is working properly.
Depending of the content of the $receivers array try either
foreach ($receivers as $value){
echo getName($value) ;
}
or
foreach ($receivers as $key => $value){
echo getName($key) ;
}

PHP foreach Loop Element Index

I have an XPath query that gets Genres of a movie.
$genreXpath = $xml_data->xpath("//category");
I get the attributes from $genreXpath like this
$genreName=array();
$genresID=array();
$i=0;
foreach($genreXpath as $node) {
$genre = $node->attributes();
$genreName[$i] = $node["name"];
$genresID[$i] = $node["id"];
$i++;
}
I'm going to be writing these values to a Db hence the two different arrays.
This code works but I know there has to be a better way of doing this be it with a 2 d array, not using a $i counter or something more obvious that I haven't figured out....any pointers???
foreach($genreXpath as $i=>$node) { //note $i is your index of the current $node
$genre = $node->attributes();
$genreName[$i] = $node["name"];
$genresID[$i] = $node["id"];
}
It auto increments and you do not need to declare it above.
Use foreach($genreXpath as $key => $node) {
If you looking to a multidimensional you could do:
$genres = array();
foreach($genreXpath as $node) {
$genre = $node->attributes();
$genres[] = array($node["name"], $node["id"]);
}

php string name as variable in array

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/

Categories