Hi am trying to read a directory for html files and put them in array and retrieve one by one.
i used following code
$filelist = glob($directory."/*.html");
$val=natsort($filelist); // Sort the array
foreach($filelist as $key => $value)
{
echo " $value , ";
}
$next=0;
$ns=$next+"1";
$filelist1=$filelist[$ns];
echo $filelist1;
am getting html files in a array but not able to retrieve one by one
please suggest
Thanks
That's echoing each item, not returning an array. Maybe it would be more clear if you change
echo " $value , ";
to
echo "ITEM $value ENDITEM , ";
Works for me
$directory = "./dir";
$filelist = glob($directory."/*.html");
sort($filelist);
foreach ($filelist as $filename) {
echo "$filename, ";
}
Also you may use
echo implode(', ', $filelist);
Instead of foreach
Return result like this:
./dir/christmas_en.html, ./dir/christmas_fr.html, ./dir/etpl_winphone.html,
Related
I'm trying to parse a json file into a for each loop. The issue is the data is nested in containers with incremented numbers, which is an issue as I can't then just grab each value in the foreach. I've spent a while trying to find a way to get this to work and I've come up empty. Any idea?
Here is the json file tidied up so you can see what I mean - http://www.jsoneditoronline.org/?url=http://ergast.com/api/f1/current/last/results.json
I am trying to get values such as [number] but I also want to get deeper values such as [Driver][code]
<?php
// get ergast json feed for next race
$url = "http://ergast.com/api/f1/current/last/results.json";
// store array in $nextRace
$json = file_get_contents($url);
$nextRace = json_decode($json, TRUE);
$a = 0;
// get array for next race
// get date and figure out how many days remaining
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][' . $a++ . '];
foreach ($nextRaceDate['data'] as $key=>$val) {
echo $val['number'];
}
?>
While decoding the json there's no need to flatten the object to an Associative array. Just use it how it is supposed to be used.
$nextRace = json_decode($json);
$nextRaceDate = $nextRace->MRData->RaceTable->Races[0]->Results;
foreach($nextRaceDate as $race){
echo 'Race number : ' . $race->number . '<br>';
echo 'Race Points : ' . $race->points. '<br>';
echo '====================' . '<br>';
}
CodePad Example
You are nearly correct with your code, you are doing it wrong when you try the $a++. Remove the $a = 0, you won't need it.
Till here you are correct
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results']
What you have to do next is this
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'];
foreach($nextRaceDate as $key => $value){
foreach($value as $key2 => $value2)
print_r($value2);
So, in my code, you are stopping at Results, and then, you want to iterate over all the results, from 0 to X, the first foreach will do that, you have to access $value for that. So, add another foreach to iterate over all the content that $value has.
There you go, I added a print_r to show you that you are iterating over what you wanted.
The problem is how you access to the elements in the nested array.
Here a way to do it:
$mrData = json_decode($json, true)['MRData'];
foreach($nextRace['RaceTable']['Races'] as $race) {
// Here you have access to race's informations
echo $race['raceName'];
echo $race['round'];
// ...
foreach($race['Results'] as $result) {
// And here to a result
echo $result['number'];
echo $result['position'];
// ...
}
}
I don't know where come's from your object, but, if you're sure that you'll get everytime one race, the first loop could be suppressed and use the shortcut:
$race = json_decode($json, true)['MRData']['RaceTable']['Races'][0];
Your problem is that the index must be an integer because the array is non associative. Giving a string, php was looking for the key '$a++', and not the index with the value in $a.
If you need only the number of the first race, try this way
$a = 0;
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races']['0']['Results'][$a];
echo "\n".$nextRaceDate['number'];
maybe you need to iterate in the 'Races' attribute
If you need all, try this way :
$nextRaceDate = $nextRace['MRData']['RaceTable']['Races'];
foreach ($nextRaceDate as $key => $val) {
foreach ($val['Results'] as $val2) {
echo "\nNUMBER " . $val2['number'];
}
}
I have an array containing strings of URLs, however some of the array elements are also an array. So some might be http://google.com, others might be:
Array([0] => http://yahoo.com [1] => http://msn.com)
I am trying to add a list of all these urls to a database. However, I need the list to expand for the multi-dimensional array. i.e. the list I am trying to establish should look like:
http://google.com
http://yahoo.com
http://msn.com
So I was initially doing this through a foreach, and then I thought I could expand the multi-dimensional arrays with a foreach within a foreach, but not sure that works. This is what I have currently, but doesnt work.
foreach($allfiles as $file) {
if(is_array($file)) {
$files = $file {
foreach($files as $file)
}
}
$qry2 = mysqli_query($con,"INSERT INTO files(name) VALUES($file)");
echo '<br>'.$file;
if($qry2) echo ' -success';
else echo ' -error';
}
You can make a recursive function to dig into your array.
Take a look at this explanation
function recursiveInsert($allfiles) {
foreach($allfiles as $file) {
if(is_array($file)) {
recursiveInsert($file);
continue;
}
$qry2 = mysqli_query($con,"INSERT INTO files(name) VALUES($file)");
echo '<br>'.$file;
if($qry2) echo ' -success';
else echo ' -error';
}
}
include 'api/apiBase.php';
$farray[] = GetUserFriends($login->User_id);
foreach ($farray as $FID)
{
echo "$FID \n";
}
My foreach loop won't echo out the array.
the function that i have GetUserFriends Returns 2 variables in a array.
Ok comments dont seem to be working so change your code to this
include 'api/apiBase.php';
// following line changed
$farray = GetUserFriends($login->User_id);
echo $login->User_id . ' has ' . count($farray) . ' friends';
foreach ($farray as $idx => $value)
{
echo "Friend $idx has FriendId $value \n";
}
This line $farray[] = GetUserFriends($login->User_id); with the extra [] in is adding another level to the $farray that you dont need and is confusing you.
That's because you're putting the friends array inside another array, like several comments say. – Barmar
Ohh the error was in my function :) Thanks
I have a mySQL query that dumps into an array, is sorted and then displayed, and that works perfectly.
My problem is that I want to update these values, re-sort them and display. I've been able to update the values, but it's within the same for loop and so it doesn't re-sort. So then I close the loop and re-sort but it doesn't save the updates I made in the first loop. Help is much appreciated.
foreach ($arr as $mks){
if ($mks['Column1']==$Var) {$mks['Column2'] = $mks['Column2'] + 1;
}
My sorting code
foreach ($arr as $mks){
echo $mks['Column1'] . ", " . $mks['Column2'] . "<br>";
}
How do I get this to re-save into my array properly?! I've tried googling this for most of the morning but has lead to frustration.
I think this is what you need:
foreach ($arr as $key => $mks){
if ($mks[$key] == $Var) {
$arr[$key] = $mks+1;
}
}
Now, $arr will contain the modified array, and you can use / modify it further as you need.
I don't see any "sorting code" but you can try to use references "&" instead of copy vars in your foreach(s) :
foreach($arr as & $mks){
...
}
Instead of copying your cells it will to give you a reference and every modifications done on it will be saved in the array.
Try changing your array like this instead
foreach ($arr as $key => $mks){
if ($mks['Column1']==$Var) {$arr[$key]['Column2'] = $mks['Column2'] + 1;
}
i am tring to put a loop to echo a number inside an echo ;
and i tried as bellow :
$array = array();
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
while($row = mysql_fetch_row($result) ){
$result_tb = mysql_query("SELECT id FROM $row[0] LIMIT 1");
$row_tb=mysql_fetch_array($result_tb);
$array[] = $row[0];
$array2[] = $row_tb[0];
//checking for availbility of result_tb
/* if (!$result_tb) {
echo "DB Error, could not list tablesn";
echo 'MySQL Error: ' . mysql_error();
exit;
} */
}
natsort($array);
natsort($array2);
foreach ($array as $item[0] ) {
echo "<a href=show_cls_db.php?id= foreach ($array2 as $item2[0]){echo \"$item2[0]\"}>{$item[0]}<br/><a/>" ;
}
but php is not considering foreach loop inside that echo ;
please suggest me something
As mentioned by others, you cannot do loops inside a string. What you are trying to do can be achieved like this:
foreach ($array as $element) {
echo "<a href='show_cls_db.php?id=" . implode('', $array2) . "'>{$element}</a><br/>";
}
implode(...) concatenates all values of the array, with a separator, which can be an empty string too.
Notes:
I think you want <br /> outside of <a>...</a>
I don't see why you would want to used $item[0] as a temporary storage for traverser array elements (hence renamed to $element)
Just use implode instead of trying to loop the array,
foreach ($array as $item)
{
echo implode("",$array2);
}
other wise if you need to do other logic for each variable then you can do something like so:
foreach ($array as $item)
{
echo '<a href="show_details.php?';
foreach($something as $something_else)
{
echo $something_else;
}
echo '">Value</a>';
}
we would have to see the contents of the variables to understand what your trying to do.
As a wild guess I would think your array look's like:
array(
id => value
)
And as you was trying to access [0] within the value produced by the initial foreach, you might be trying to get the key and value separate, try something like this:
foreach($array as $id => $value)
{
echo $id; //This should be the index
echo $value; //This should be the value
}
foreach ($array as $item ) {
echo "<a href=\"show_cls_db.php?id=";
foreach ($array2 as $item2) { echo $item2[0]; }
echo "\">{$item[0]}<br/><a/>" ;
}
No offense but this code is... rough. Post it on codereview.stackexchange.com for some help re-factoring it. A quick tip for now would be to use PDO, and at the least, escape your inputs.
Anyway, as the answers have pointed out, you have simply echoed out a string with the "foreach" code inside it. Take it out of the string. I would probably use implode as RobertPitt suggested. Consider sorting and selecting your data from your database more efficiently by having mysql do the sorting. Don't use as $item[0] as that makes absolutely no sense at all. Name your variables clearly. Additionally, your href tag is malformed - you may not see the correct results even when you pull the foreach loop out of the echo, as your browser may render it all away. Make sure to put those quotes where they should be.