In the following php code, I am getting the above error. $strings stores the fields coming from database as an array. So why is this error coming? Can someone tells me the solution for this problem, please.
$db_selected = mysql_select_db("chatter",$con);
$mvsql="Select body from feed";
$str=mysql_query($mvsql,$con);$i=0;
while($strings=mysql_fetch_array($str)){
echo $strings["body"] . "<br>";
}
require_once __DIR__ . '/../autoload.php';
$sentiment = new \PHPInsight\Sentiment();
foreach ($strings as $string) {
// calculations:
$scores = $sentiment->score($string);
$class = $sentiment->categorise($string);
// output:
echo "String: $string\n";
echo "Dominant: $class, scores: ";
print_r($scores);
echo "\n";
}
Add this row in your while loop, and use the foreacn on this:
$stringsArr[] = $strings["body"];
Do not use mysql_ functions, because they are deprecated. Use mysqli_ or PDO instead.
while($strings=mysql_fetch_array($str)): the last iteration of the loop, mysql_fetch_array returns false (no more rows). So after this loop, when you go in your foreach loop, $string is false. Just execute your instructions inside the while loop, for each row.
$db_selected = mysql_select_db("chatter",$con);
$mvsql="Select body from feed";
$str=mysql_query($mvsql,$con);$i=0;
require_once __DIR__ . '/../autoload.php';
$sentiment = new \PHPInsight\Sentiment();
while($strings=mysql_fetch_array($str)){
$body = $strings['body'];
// calculations:
$scores = $sentiment->score($body);
$class = $sentiment->categorise($body);
// output:
echo "String: $body\n";
echo "Dominant: $class, scores: ";
print_r($scores);
echo "\n";
}
Please also read this post: Why shouldn't I use mysql_* functions in PHP? , very useful.
You iterate until mysql_fetch_array($str) returns false. I.e. until $strings is no longer an array. foreach expects $strings to be an array.
$strings will be FALSE when the foreach starts.
This is because of the while above it. This loop will loop through all records, till mysql_fetch_array($str) returns FALSE and thus terminates the loop.
You should probably put the foreach code inside the while loop or use the while loop to collect the items you need and loop through those in the foreach loop.
Related
I'm using Kucoin's API to get a list of coins.
Here is the endpoint: https://api.kucoin.com/v1/market/open/coins
And here's my code:
$kucoin_coins = file_get_contents('https://api.kucoin.com/v1/market/open/coins');
$kucoin_coins = json_decode($kucoin_coins, true);
print_r($kucoin_coins);
I can see how to target one coin like so:
echo "name: " . $kucoin_coins['data'][0]['name'];
But I can't see how to loop through them.
How can I loop through each of the "coins" returned here? They are under the "data" part that is returned. I'm sorry, I'm just not seeing how to do it right now. Thank you!
You can loop through the decoded elements using the foreach command:
foreach ($kucoin_coins['data'] as $coin) {
//do your magic here.
}
But I usually prefer using json_decode($kucoin_coins) rather than the one for arrays. I believe this:
$item->attribute;
Is easier to write than this one:
$item['attribute'];
foreach($kucoin_coins['data'] as $data) {
echo $data['name']."\n";
}
You can loop through your data using foreach() like this
<?php
$kucoin_coins = file_get_contents('https://api.kucoin.com/v1/market/open/coins');
$kucoin_coins = json_decode($kucoin_coins, true);
print '<pre>';
print_r($kucoin_coins);
print '</pre>';
foreach($kucoin_coins['data'] as $key=>$value){
echo $value['name']. "<br/>";
}
?>
See DEMO: http://phpfiddle.org/main/code/q6kt-dctg
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'];
}
}
So, guys, my problem is that i'm creating an array from a mysql column, but, when i echo the array items, it returns me nothing, i'm about this for a while and i'm not seeing a possible error, hope can get some help. Here' s my code: (I know about the mysql to mysqli, but i'm just beginning and trying the logical stuff. :))
$duracao = mysql_query(
"SELECT SUM(fim_periodo-inicio_periodo)/0.01666667 AS mysum
FROM afunda_eleva_$a"
); //THIS $duracao IS INSIDE A FOR LOOP THAT EXECUTES THE QUERY IF A CONDITION IS SATISFIED (DEPENDING ON $a and $prevNum), it is working fine!
while ($row2 = mysql_fetch_assoc($duracao))
{
$duracao_afunda_eleva[] = $row2['mysum'];
}
so, to test some possible problems, i've put:
$i2 = sizeof($duracao_afunda_eleva);
echo $i2;
echo <br>;
which returns me the right size of the array, the problem comes here, i think:
for($i1 = 0 ; $i1 < sizeof($duracao_afunda_eleva); $i1++)
{
echo $duracao_afunda_eleva[$i1] or die("couldn't echo"
. mysql_error());
echo "<br>";
}
and this returns me no value. I really would appreciate any suggestion. Thanks in advance!
Try print_r instead of echo - echo outputs (string)$variable, which in case of an array is just "array". Also, echo is a language construct and not a function, so your or die(...) is problematic, as language constructs don't have return values.
Generally it's better to not use or die(...) constructs, and handle problems correctly (using a defined return value, so cleanup code can run, for example). Also, not being able to output anything with echo would mean that your php/whatever installation is seriously gone bad, at which point you probably won't even reach that line in your code, and even then it won't have anything to do with mysql.
Since the problem is not in the variable, try to use an alias in your MySQL select:
SELECT SUM(fim_periodo-inicio_periodo)/0.01666667 as mysum
Then in your PHP, you can get $row2['mysum'];
It may not solve the problem, but it is a good start.
Personally I use:
$arr = array ( /* ... */ );
echo "<pre>";
var_dump($arr);
echo "</pre>";
In your last for-loop, you use $i++, it should be $i1++
A quick tip is not to use the sizeof function in your for loop. This gets run with each iteration of your loop and you will notice an improvement in performance if you move it outside the loop (or use a foreach loop instead). e.g.
$count = sizeof($duracao_afunda_eleva);
for($i = 0 ; $i < $count; $i++) {
echo $duracao_afunda_eleva[$i] . '<br />';
}
or
// Foreach loop example
foreach ($duracao_afunda_eleva as $key => $value) {
echo $value . '<br />';
}
or what you could also do is this one line
echo implode('<br />', $duracao_afunda_eleva);
Use this code:
for($i1 = 0 ; $i1 < sizeof($duracao_afunda_eleva); $i1++)
{
echo $duracao_afunda_eleva[$i1] or die("couldn't echo". mysql_error());
echo "<br>";
}
You increased $i instead of $i1.
Although, with arrays, it's usually easier to use a foreach loop.
This runs from the first to the last element in the array.
Like so:
foreach ($duracao_afunda_eleva as $value) {
echo $value;
}
I would also suggest removing the space in $row2 ['mysum']:
$duracao_afunda_eleva[] = $row2['mysum'];
Edit
Just noticed it now, but your fetch-statement is wrong... It has a typo in it:
while ($row2 = mysql_fetch_assoc($duracao))
Make sure it reads mysql instead of myqsl.
I need to iterate through data pulled from an mssql database twice in my php, but I find that when I perform the first foreach loop the array is then listed as empty as the array pointer has moved through the entire array.
In essence I have this:
$rstGold = $rstGold2 = getFeatured();
foreach($rstGold as $store){
//proccessing here
}
foreach($rstGold2 as $store){
//proccessing here
}
get featured is a sql query returning results using the mssql-PDO driver.
function getFeatured(){
global $db, $debug;
$query = //sql query
return $db->query($query);
}
I need a way to iterate through the results of getFeatured() twice, with them remaining in the same order. My sql query randomizes the results so I cannot perform a second sql query.
While writing this I found a way to perform all of the processing in the same loop, but would still like to know what the best way to do this would be.
Use an ArrayIterator, per the docs:
When you want to iterate over the same array multiple times you need
to instantiate ArrayObject and let it create ArrayIterator instances
that refer to it either by using foreach or by calling its
getIterator() method manually.
And the example follows:
<?php
$fruits = array(
"apple" => "yummy",
"orange" => "ah ya, nice",
"grape" => "wow, I love it!",
"plum" => "nah, not me"
);
$obj = new ArrayObject( $fruits );
$it = $obj->getIterator();
// How many items are we iterating over?
echo "Iterating over: " . $obj->count() . " values\n";
// Iterate over the values in the ArrayObject:
while( $it->valid() )
{
echo $it->key() . "=" . $it->current() . "\n";
$it->next();
}
// The good thing here is that it can be iterated with foreach loop
foreach ($it as $key=>$val)
echo $key.":".$val."\n";
The class also has a method to reset the pointer to the beginning called rewind, used as follows:
$iterator = $arrayobject->getIterator();
$iterator->next();
echo $iterator->key(); //1
$iterator->rewind(); //rewinding to the begining
Hope that helps.
<div class="meta">
<?php echo $submitted."pubblished in".$fenl; ?>
<a href="<?php echo base_path().'comp/'.$node->nid;?>">
<?php echo $comment_count;?>comment</a>
</div>
it there a better way to write the above code.
2,
function blog_gettag(){
$terms = mysql_query('SELECT vid,name FROM term WHERE vid=2');
$items = array();
foreach ($terms as $term){
$items[] = $term->name;
}
return $items;
}
could i delete $items = array(); this line. thank you.
Not really, unless you count the short-tags, but they are frowned on.
Technically, it would be created automatically, but you should pre-declare the empty array, it should generate a warning if you did not.
NB. If you have two separate questions, they should be asked separately in future.
What about one line?
<?php
echo "<div class=\"meta\">\n{$submitted}published in$fenl\n<a href=\"" .
base_path() . "comp/{$node->nid}\">\n$comment_count\ncomment</a>\n</div>";
?>
You could delete $items = array(); as long as $items isn't used before in your script (just don't return $items in case $terms isn't an array and the foreach loop gets called, as the situation seems to be at the moment). I believe you need to check mysql_query() examples at http://php.net/manual/en/function.mysql-query.php.
It's syntactically pretty okay. As far as I know, you could omit $items = array(); but I find it more readable if you just leave it as it is.
Btw.: Don't you need to use mysql_fetch_assoc for your iteration? mysql_query returns a resource.
echo "<div class=\"meta\">" . $submitted . " pubblished in " . $fenl . "" . $comment_count . " comment</div>";
You don't need to define array. But in this case ( foreach issue. Foreach loop requires an array as parameter to left side the "as". If you delete that line $items wouldn't be an array.It will be a null variable.So you will get a warning. ) it should be defined.