I´ve got the following:
include('php/get_recipe_byID.php');
$jsonstring1 = $recipe_byidarr;
$recip = json_decode($recipe_byidarr, true);
print_r($recip);
foreach ($recip['Data']['Recipes'] as $key => $newrecipe) {
// echo '<li>
// <a href="/recipe_search.php?id=' . $recipe['ID'] . '">';
echo 'seas';
echo $newrecipe['TITLE'];
echo '<br><br>';
}
When I call it in the browser, it tells me that
Fatal error: Cannot use string offset as an array in /var/www/recipe_search.php on line 43
This is the line of the foreach loop.
$recip is the following:
{"Data":{"Recipes":{"Recipe_9":{"ID":"9","TITLE":"Schnitzel","TEXT":"Alex\u00b4s Hausmannskost","COUNT_PERSONS":"4","DURATION":"40","USER_ID":"1","DATE":"2011-09-16 00:00:00"}}},"Message":null,"Code":200}
Do anybody know where my mistake is?
Just try it:
$taskSeries = $array['Data']['Recipes']['Recipe_'.$_GET['id']];
if(array_key_exists('TITLE', $taskSeries)) {
$taskSeries = array($taskSeries);
}
foreach($taskSeries as $task) {
$title = $task['TITLE'];
// do something with $title and other
}
Related
I've been trying to get further in PHP and writing functions daily to practice but started to get the feeling I'm either overcomplicating or doing it completely wrong.
My 2 functions for this script:
function getFilesAndContent($path)
{
$data = [];
$folderContents = new DirectoryIterator($path);
foreach ($folderContents as $fileInfo) {
if ($fileInfo->isDot()) {
break;
}
$fileData = [
'file_name' => $fileInfo->getName(),
];
if ($fileInfo->getExtension()) {
$fileData['contents'] = getFileContents($fileInfo->getPathname());
}
$data = $fileData;
}
return $data;
}
function getFileContents($path)
{
$names = file_get_contents($fileInfo->getPathname());
$names = implode("\n", $names);
sort($names);
$contents = '';
foreach ($names as $name) {
$contents += $name . ' (' . strlen($name) . ')<br>';
}
return $name;
}
All I want to do is:
foreach (getFilesAndContent('.') as $data) {
echo $data['file_name'];
echo '<br>';
echo $data['contents'];
echo '<hr>';
The error:
FATAL ERROR Uncaught Error: Call to undefined method DirectoryIterator::getName() in /home4/phptest/public_html/code.php70(5) : eval()'d code:15 Stack trace: #0 /home4/phptest/public_html/code.php70(5) : eval()'d code(45): getFilesAndContent('.') #1 /home4/phptest/public_html/code.php70(5): eval() #2 {main} thrown on line number 15
The file it's supposed to read is a simple .txt files with a list of names, nothing more.
Any help appreciated! Also wondering if it's better to just rewrite the entire functions if I keep getting so many errors?
You have many things to fix in your code, for example changing undefined method getName() to something else, don't use break to skip because it will exit the loop, using explode(string $separator, string $string) to split string by separator, return $contents from getFileContents() function to return final concatenated string, etc.
I think, your goal is to display all *.txt files and its contents, with length for each line in contents. Try this:
$d = dir('.');
while (($file = $d->read()) !== false) { // iterate all files
if (preg_match('/\.txt$/', $file)) { // filter only file ends with .txt
$contents = explode("\n", file_get_contents($d->path . '/' . $file)); // get file contents, split by \n
array_walk($contents, function(&$item) {
$item .= ' (' . strlen($item) . ')';
}); // add (length) in the end of each line
// display it
echo '<strong>' . $file . '</strong><br>';
echo implode('<br>', $contents);
echo '<hr>';
}
}
I want to show a list of TV programs with title, genre, subgenre, description, start time and duration using a json file on server but I get the following errors:
E_NOTICE : type 8 -- Trying to get property of non-object -- at line 13
E_WARNING : type 2 -- Invalid argument supplied for foreach() -- at line 13
Here is a piece of a sample json:
{"channel":"6280",
"banned":true,
"plan":[
{"id":"-1",
"pid":"0",
"starttime":"00:00",
"dur":"65",
"title":"",
"normalizedtitle": "",
"desc":"",
"genre":"",
"subgenre":"",
"prima":false
},
{"id":"94622386",
"pid":"507461",
"starttime":"01:05",
"dur":"65",
"title":"Sex Researchers",
"normalizedtitle": "sex-researchers",
"desc":"Ep. 2 - Ciclo The Body of...",
"genre":"mondo e tendenze",
"subgenre":"societa",
"prima":false
},
Here is the php code that I use:
<?php
$channel = '6280';
$current_unix = time();
$json = json_decode(file_get_contents('http://guidatv.sky.it/app/guidatv/contenuti/data/grid/'.date('y_m_d').'/ch_'.$channel.'.js'));
//print_r($json);
echo '<ul>';
foreach ($json as $data) {
echo '<li>';
foreach ($data->plan as $prog) {
if ( $current_unix < $prog->starttime ) {
echo $prog->id . '<br>';
echo $prog->starttime . '<br>';
echo $prog->dur . '<br>';
echo $prog->desc . '<br>';
if ( isset($prog->genre)) {
echo $prog->genre . '<br>';
}
}
}
echo '</li>';
}
echo '</ul>';
?>
Could you help me to solve this problem? Thank you
You cannot loop on the object. Your JSON does not return the array of channel, but return only a channel object. Here is what you want:
$json = json_decode(file_get_contents('http://guidatv.sky.it/app/guidatv/contenuti/data/grid/'.date('y_m_d').'/ch_'.$channel.'.js'));
echo '<ul>';
foreach ($json->plan as $prog) {
echo "<li>" . $prog->title . '</li>';
}
echo '</ul>';
I'm trying to use this function at the bottom of a plugin's main PHP file to determine if one of its action hooks is being used by the tag specified. However, I'm getting a "Warning" on the 2nd foreach in the code below. Why is this? Is there a better way to see if a Wordpress action hook is being used?
<?php
function dump_hook($tag, $hook)
{
ksort($hook);
echo "<pre>>>>>>\t$tag<br>";
foreach ($hook as $priority => $functions) {
echo $priority;
foreach ($functions as $function) {
if ($function['function'] != 'list_hook_details') {
echo "\t";
if (is_string($function['function']))
echo $function['function'];
elseif (is_string($function['function'][0]))
echo $function['function'][0] . ' -> ' . $function['function'][1];
elseif (is_object($function['function'][0]))
echo "(object) " . get_class($function['function'][0]) . ' -> ' . $function['function'][1];
else
print_r($function);
echo ' (' . $function['accepted_args'] . ') <br>';
}
}
}
echo '</pre>';
}
$tag = array('anspress_loaded');
$hook = array('find_do_for_anspress');
dump_hook($tag, $hook);
Some errors from your code:
1.) $tag is array, but in your function it's used as string:
<?php
echo "<pre>>>>>>\t$tag<br>";
2.)$hook is array, so first foreach works ok:
<?php
// for first row
// $priority is int 0
// $functions is string find_do_for_anspress
foreach($hook as $priority => $functions ) {}
Next you try to do foreach with string $functions, but it's not iterrable, so php says to you aforementioned error.
foreach ($data['tests'] as $testname => $tests) {
echo "<h1>Extraction $testname Tests</h1>\n";
$function = $testfunctions[$testname];
echo "<ul>";
foreach ($tests as $test) {
echo "<li>" . $test['description'] . ' ... ';
$extracted = $extractor->$function($test['text']);
if ($test['expected'] == $extracted) {
echo " <span style='color: green'>passed.</span></li>";
} else {
echo " <span style='color: red'>failed.</span>";
echo "<pre>Original: " . htmlspecialchars($test['text']) . "\nExpected: " . print_r($test['expected'], true) . "\nActual : " . print_r($extracted, true) . "</pre>";
}
echo "</li>";
}
echo "</ul>";}
I keep getting the error:
Warning: Invalid argument supplied for
foreach() in
C:\xampp\htdocs\test\runtests.php on
line 49
p.s. the beginning of the code is line 49, so the probelm starts with the foreach statment.
Whenever i see that, it tends to mean that the thing i'm trying to iterate through isn't an array.
Check $data['tests'] (and each inner $tests) to make sure it's not null/unset/empty, and that it's something iterable like an array. Also keep in mind that older versions of PHP (before 5.0?) don't do iterable objects very well.
One of the elements in $data["tests"] is probably not an array.
Add this before the foreach:
if (is_array($tests))
foreach ($tests as $test) {...
im getting this error:
Parse error: syntax error, unexpected T_ECHO in /home/labvc/public_html/AT/site/getimages.php on line 26
from this code:
<?php
echo '<br />';
echo '<div id=gallery>';
function getDirTree($dir,$p=true) {
$d = dir($dir);$x=array();
while (false !== ($r = $d->read())) {
if($r!="."&&$r!=".."&&(($p==false&&is_dir($dir.$r))||$p==true)) {
$x[$r] = (is_dir($dir.$r)?array():(is_file($dir.$r)?true:false));
}
}
foreach ($x as $key => $value) {
if (is_dir($dir.$key."/")) {
$x[$key] = getDirTree($dir.$key."/",$p);
}
}
ksort($x);
return $x;
}
$tree = getDirTree("./res/gallery/painting/");
foreach($tree as $element => $eval) {
if (is_array($eval)) {
foreach($eval as $file => $value) {
if (strstr($file, "png")||strstr($file, "jpg")||strstr($file, "bmp")||strstr($file, "gif")) {
$item = $tree.'/'.$element.$file;
$itemthumb = $tree.'/thumbs/'.$element.$file;
echo '<img src="'.$itemthumb.'" alt="'.$file.'"/>';
}
}
}
}
echo '</div>';
echo '<br />';
echo 'tree: '.$tree.'<br />';
echo 'element: '.$element.'<br />';
echo 'file: '.$file.'<br />';
$abc="res/gallery/painting";
$def="01.png";
echo'<img src="'.$abc.'/thumbs/'.$def.'" alt="'.$def.'"/>';
echo '<br />';
line 26 is not an echo, theres not even an echo close to line 26
foreach($tree as $element => $eval) {
Any ideas?
I know it sounds silly, but are you actually looking at / editing the file you are debugging?
Any number of times it turned out I was in directory A/foo.c, when the code was being run out of directory B/foo.c. I always feel stooooopid after doing this.
Stick a print "foo!" in there to see if you are actually in the file you think you are.
This seems a suspicious line:
$item = $tree.'/'.$element.$file;
$tree should be an array, so if you get the error at runtime (as opposed to compile time) then it would make sense it would complain about this.