I don't like to use the foreach for every little array, I hear'd it is also possible to replace it with some array_ function, but I forget the function name.
This is what I wan't to reach:
$down = array (
"file.rar" => $l->get()->fileDesc(),
"file1.rar" => $l->get()->clientDesc()
);
normally, I'm using this to display the data:
foreach ( $down as $key => $value )
$data .= $key . ' = ' . $value . '<br/>';
So it'll return:
//echo $data;
file.rar = File Description One
file1.rar = Client Description
It there a way to prevent from using the foreach and display the same $data anyway?
I'm just curious, so please be nice.
Why don't you just write your own function?
function print_array($down) {
$data = '';
foreach ( $down as $key => $value )
$data .= $key . ' = ' . $value . '<br/>';
return $data;
}
You can use print_r with true on the second parameter, but I would suggest to use a foreach (as I say in my comment)
<?php
$data = print_r($down, true);
?>
well the only time you would need to use a foreach is for a dynamic array. if thats not the case, just use isset to find out what is set. you can also use count if your just trying to figure out how big an array is.
Related
So I would like to create just one loop to parse the json data i have. I can successfully parse it in 2 foreach loops however when trying to combine in one loop using $key => $value the $key returns nothing when called. How can I successfully take the 2 foreach loops I have here and combine them into one?
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key) {
$GenreID = $key['id'].'<br>';
echo $GenreID;
}
foreach($jsonList as $key => $value) {
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
The json data is as follows:
{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"},{"id":16,"name":"Animation"},{"id":35,"name":"Comedy"},{"id":80,"name":"Crime"},{"id":99,"name":"Documentary"},{"id":18,"name":"Drama"},{"id":10751,"name":"Family"},{"id":14,"name":"Fantasy"},{"id":36,"name":"History"},{"id":27,"name":"Horror"},{"id":10402,"name":"Music"},{"id":9648,"name":"Mystery"},{"id":10749,"name":"Romance"},{"id":878,"name":"Science Fiction"},{"id":10770,"name":"TV Movie"},{"id":53,"name":"Thriller"},{"id":10752,"name":"War"},{"id":37,"name":"Western"}]}
You can still use $key as an index when also extracting the $value.
However note that you shouldn't be assigning the line breaks to your variables, and should instead consider them part of the view by echoing them out independently:
$contents = file_get_contents($url);
$results = json_decode($contents, true);
$jsonList = $results['genres'];
foreach($jsonList as $key => $value) {
$GenreID = $key['id']; // Depending on structure, you may need $value['id'];
$GenreName = $value['name'];
echo $GenreID . '<br>';
echo $GenreName . '<br><br>';
}
Your single loop below here.
foreach($jsonList as $key)
{
$GenreID = $key['id'].'<br>';
echo $GenreID;
$GenreName = $value['name'].'<br><br>';
echo $GenreName;
}
$key is a assosative array.Therefore it had some index.So you can use this index in single loop.
It seems you get confused over your data structure. Seeing the json, the resulting "$jsonlist" supposed to contain array with id and value as keys.
You can iterate over it and extract the the appropriate key.
Myabe something like this:
foreach($jsonlist as $value) {
echo "id: " . $value['id'] . "\n";
echo "name: " . $value['name'] . "\n";
}
extra bonus, if you want to create 1 level array from your json based on id with the name you could try array reduce using anon function like this:
$jsonlist = array_reduce($jsonlist, function($result, $item){
$result[$item['id']] = $item['name'];
return $result;
}, []);
extra neat for transformation of static structure data.
I have seen a bunch of ways, but none that seem to work. My array data is coming back like this.
Array
(
[0] => RESULT=0
[1] => RESPMSG=Approved
[2] => SECURETOKEN=8cpcwfZhaH02qNlIoFEGZ1wO4
[3] => SECURETOKENID=253cad735251571cebcea28e877f4fd7
I use this:
<?php echo $response[2];?>
too get each out, that works. But I need to remove “SECURETOKEN=” so im left with just the number strings. I have been trying something like this with out success.
function test($response){
$secure_token = $response[1];
$secure_token = substr($secure_token, -25);
return $secure_token;
}
Also Im putting end number into a form input “Value” field. Not that that matters, unless it does?
Thanks
This is what I would do:
$keyResponse = [];
foreach ($response as $item) {
list($k, $v) = explode('=', $item, 2);
$keyResponse[$k] = $v;
}
Now you can easily access just the value part of each item based on the name:
echo $keyResponse['SECURETOKEN']; // output: 8cpcwfZhaH02qNlIoFEGZ1wO4
The advantage to this method is the code still works if the order of the items in $response changes
I get your secure token like this (tested):
<?php
$arr = array(
'RESULT=0',
'RESPMSG=Approved',
'SECURETOKEN=8cpcwfZhaH02qNlIoFEGZ1wO4',
'SECURETOKENID=253cad735251571cebcea28e877f4fd7'
);
$el = $arr[2];
$parts = explode('=', $el);
echo '#1 SECURETOKEN is ' . $parts[1];
// This break just for testing
echo '<br />';
// If you wanted to, you could revise the whole array
$new = array();
foreach( $arr as $el ){
$parts = explode('=', $el);
$new[$parts[0]] = $parts[1];
}
// Which would mean you could then get your securetoken like this:
echo '#2 SECURETOKEN is ' . $new['SECURETOKEN'];
I wanted to ask, how can i modify array values when doing foreach - in my example, i want to add to every element, but this code produces error.
foreach ($logo as &$value) {
$value = '<div>' . $value . '</div>';
debug ($value);
}
?>
and the error: Notice (8): Array to string conversion
I'm using php 5.6
Thanks for reply.
I use
$serviceMe = ""; //OR use beginning html
foreach( $tmp as $t ) $serviceMe .= '<tr>' . $t . '</tr>';
$serviceMe .= ""; // Rest of the needed html
Make absolutely sure what type of is your $value. Is it integer,float,string,object,array... etc
I think your error comes from trying to convert array to string without proper handling.
$array = new array(
'key' => $value,
'key2' => $value2,
'key3' => $value3,
);
$string = "" . $array; //throws error!
I am using a URL to fetch data stored/shown within URL. I get all the value of variable using $_REQUEST['v_name'] but if there is a array in URL how can i retrieve that value.
For Example:
WWW.example.com/rooms?&hid=213421&type=E
I got the value hid and type using
$hid=$_REQUEST['hid'];
but in URL like:
WWW.example.com/rooms?&rooms=2&rooms[0].adults=2&rooms[0].children=0&rooms[1].adults=2&rooms[1].children=0
how can i retrieve value of adults and children in each room.
please help.
Thanks in Advance
You could also try something like this, since most of your original $_REQUEST isn't really an array (because of the .s in between each key/value pair):
<?php
$original_string = rawurldecode($_SERVER["QUERY_STRING"]);
$original_string_split = preg_split('/&/', $original_string);
$rooms = array();
foreach ($original_string_split as $split_one) {
$splits_two[] = preg_split('/\./', $split_one);
}
foreach ($splits_two as $split_two) {
if (isset($split_two[0]) && isset($split_two[1])) {
$split_three = preg_split('/=/', $split_two[1]);
if (isset($split_three[0]) && isset($split_three[1])) {
$rooms[$split_two[0]][$split_three[0]] = $split_three[1];
}
}
}
// Print the output if you want:
print '<pre>' . print_r($rooms, 1) . '</pre>';
$valuse = $_GET;
foreach ($valuse as $key=>$value)
{
echo $key .'='. $value. '<br/>';
}
function example()
{
foreach ($choices as $key => $choice) { # \__ both should run parallel
foreach ($vtitles as $keystwo => $vtitle) { # /
$options .= '<option value="'. check_plain($key) .'" title="' . $vtitle . '"' . $selected
.'>'. check_plain($choice) .'</option>';
} // end of vtitle
} // end of choice
return $options;
}
Answers to some of the below questions and what I am trying to achieve.
Array $choices is not numerically indexed.
Array $vtitle is numerically indexed.
They won't be shorter than each other as I have code which will take care of this before this code runs.
I am trying to return $options variable. The issue is that $choices[0] and $vtitle[0] should be used only once. Hope I was able to express my problem.
I do not want to go through the $vtitles array once for each value in $choices.
#hakre: thanks I have nearly solved it with your help.
I am getting an error for variable $vtitle:
InvalidArgumentException: Passed variable is not an array or object, using empty array
instead in ArrayIterator->__construct() (line 35 of /home/vishal/Dropbox/sites/chatter/sites
/all/themes/kt_vusers/template.php).
I am sure its an array this is the output using print_r
Array ( [0] => vishalkh [1] => newandold )
What might be going wrong ?
The below worked for me , thank you hakre
while
(
(list($key1, $value1) = each($array1))
&& (list($key2, $value2) = each($array2))
)
{
printf("%s => %s, %s => %s \n", $key1, $value1, $key2, $value2);
}
It does not work the way you outline with your pseudo code. However, the SPL offers a way to iterate multiple iterators at once. It's called MultipleIterator and you can attach as many iterators as you like:
$multi = new MultipleIterator();
$multi->attachIterator(new ArrayIterator($array1));
$multi->attachIterator(new ArrayIterator($array2));
foreach($multi as $value)
{
list($key1, $key2) = $multi->key();
list($value1, $value2) = $value;
}
See it in action: Demo
Edit: The first example shows a suggestion from the SPL. It has the benefit that it can deal with any kind of iterators, not only arrays. If you want to express something similar with arrays, you can achieve something similar with the classic while(list()=each()) loop, which allows more expressions than foreach.
while
(
(list($key1, $value1) = each($array1))
&& (list($key2, $value2) = each($array2))
)
{
printf("%s => %s, %s => %s \n", $key1, $value1, $key2, $value2);
}
Demo (the minimum number of elements are iterated)
See as well a related question: Multiple index variables in PHP foreach loop
you can't do it in foreach loop in general case. But you can do it like this in PHP5:
$obj1 = new ArrayObject($arr1);
$it1 = $obj1->getIterator();
$obj2 = new ArrayObject($arr2);
$it2 = $obj2->getIterator();
while( $it1->valid() && $it2->valid())
{
echo $it1->key() . "=" . $it1->current() . "\n";
$it1->next();
echo $it2->key() . "=" . $it2->current() . "\n";
$it2->next();
}
In older versions of PHP it will be like this:
while (($choice = current($choices)) && ($vtitle = current($vtitles))) {
$key_choice = key($choices);
$key_vtitle = key($vtitles);
next($choices);
next($vtitles);
}
Short Answer, no.
What you can do instead is:
foreach ($array1 as $k => $v)
performMyLogic($k, $v);
foreach ($array2 as $k => $v)
performMyLogic($k, $v);
If the keys are the same, you can do this:
foreach ($choices as $key => $choice) {
$vtitle = $vtitles[$key];
}
You may have to refigure your logic to do what you want. Any reason you can't just use 2 foreach loops? Or nest one inside the other?
EDIT: as others have pointed out, if PHP did support what you're trying to do, it wouldn't be safe at all.. so it's probably a good thing that it doesn't :)
Maybe you want this:
//get theirs keys
$keys_choices = array_keys($choices);
$keys_vtitles = array_keys($vtitles);
//the same size I guess
if (count($keys_choices) === count($keys_vtitles)) {
for ($i = 0;$i < count($keys_choices); $i++) {
//First array
$key_1 = $keys_choices[$i];
$value_1 = $choices[$keys_choices[$i]];
//second_array
$key_2 = $key_vtitles[$i];
$value_2 = $vtitles[$keys_vtitles[$i]];
//and you can operate
}
}
But this will work if size is the same. But you can change this code.
You need to use two foreach loops.
foreach ($choices as $keyChoice => $choice)
{
foreach ($vtitles as $keyVtitle => $vtitle)
{
//Code to work on values here
}
}