I've been using explode in a separate foreach, but now I want to use it in existing foreach, which I find hard. Instead of the name of the screenshot it echos "Array". What am I doing wrong and how can I limit it to just one of the screenshots, not up to four?
<?php $game = Yii::app()->db->createCommand();
$game->select = 'idProgramGame, dk_name, dk_text, picture, recordType, screenshot';
$game->from = 'programsgames';
$game->where = 'dk_name IS NOT NULL';
$game->where = 'featured = 2';
$game->where = 'points = 100';
$game->where = 'recordType = "g"';
$game->order = 'date DESC';
$game->limit = '1';
$gameresult = $game->query();
foreach($gameresult as $gamerow) {
echo '<a href="http://www.domain.com/Yii/index.php/programsgames/';
echo $gamerow['idProgramGame'];
echo '">';
echo '<br><div class="image"><h2><span><b>';
echo $gamerow['dk_name'];
echo '</b></span></h2>';
echo '<center><img src="http://www.domain.com/upload/';
echo explode(';',$gamerow['screenshot']);
echo '" height="250" align="center" alt="';
echo $gamerow['dk_name'];
echo '"></center>';
echo '</a></div><br><br><br>';
}
?>
When trying to debug, you should always simplify your code as much as possible, while still getting the error.
In this case, you've already established that your echo explode(";",$gamerow['screenshot']); line is at fault here, so you should investigate explode and how it works.
In particular, you'll notice that it returns an array. Reading up on arrays will tell you that if you try to just echo it, it outputs Array, literally.
Now, I don't know what's in $gamerow['screenshot'], but I'm going to guess that it's something like this:
something.png;otherstuffhere
If that's the case, then your solution depends on if your PHP is up-to-date.
If it is, just do this:
echo explode(";",$gamerow['screenshot'])[0];
If not, you have to use a temporary variable:
$parts = explode(";",$gamerow['screenshot']);
echo $parts[0];
For future reference, to output the contents of an array for debugging purposes, use var_dump or a related function.
echo explode(';',$gamerow['screenshot']);
explode() will return an array of all values seperated by ';', but echo() can't display arrays. You could just loop through that array from explode() using foreach:
foreach(explode(';',$gamerow['screenshot']) as $screenshot){
echo($screenshot);
}
Related
I am trying to echo out my array on each line, not bunched together.
I have tried <br />, this only show's on the front end, but when you look at HTML code. Its still clumped together.
$arrays = [];
$arrays[] = "Good";
$arrays[] = "Bad";
foreach ($arrays as $array){
echo $array;
}
Result:
GoodBad
Want Result:
Good
Bad
Short of using print_r, to quickly get your desired result, just make this small change:
echo $array."\n";
Make sure it's double-quotes and it will add a new line.
(That would do what "<br />" does on HTML)
Try using print_r($arrays). docs here.
Try echo "<pre>; var_dump($arrays); echo "</pre>;
I have a PHP session array where it can be counted as multidimensional array, basically I am trying to store data inside my session array and i am successfully obtaining that part of the task. The main issue is, I am not able to echo them specifically and I have to use var_dump. When I try to print them with echo i got an notice which says array to string conversion. Please any help I would be appreciated how to print them with their own specific keys or values. The code as follows:
if (!is_array($_SESSION['products']['names'])){
$_SESSION['products']['names'] = array();
$_SESSION['products']['names']['prices']= array();
}else {
$pros = $_SESSION['products']['names'];
if (in_array($product->getName(), $pros, true)){
echo 'The product is available in your basket';
} else {
array_push($_SESSION['products']['names'],$product->getName());
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
foreach ($_SESSION['products'] as $val){
echo $val['names'];
echo $val['prices'];
}
}
}
The output that I receive as follows:
Notice: Undefined index: names in
Array to string conversion in
Use join() function in your foreach, like this:
echo join('<br>', $val);
Or instead of
echo $val['prices'];
write
echo $val['names']['prices'];
This is your problem...
// Here your assigning `['names']` as a string..
array_push($_SESSION['products']['names'],$product->getName());
// Then here you're overwriting the string with an array...
array_push($_SESSION['products']['names']['prices'], $product->getPrice(Currency::getCurrentCurrency()));
Change the first one to this..
array_push($_SESSION['products']['names']['name'],$product->getName());
Assuming $product->getPrice() returns a string or a number...
foreach ($_SESSION['products'] as $val){
foreach($val['names'] as $name){
echo $name['name'];
echo $name['prices'];
}
}
There is no issue with the code you have here. I don't see you trying to echo or vardump them directly so please show the code you are echoing them out specifically or the output from above and which line is giving you an issue.
If you want to echo each one out with it's price.
for($i=0;$i<count($_SESSION['products']['names']);$i++) {
echo $_SESSION['products']['names'][$i] . " " . $_SESSION['products']['names']['price'][$i];
}
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 am having trouble in returning data in php from an SQL query. here is my code:
public function get_audit_message($productId,$accountId)
{
$sql_list ="SELECT notes
FROM ".$this->tables_audit."
WHERE productId = '".mysql_real_escape_string($productId)."'
AND accountId = '".mysql_real_escape_string($accountId)."'
";
$query = $this->db->query($sql_list);
if($query->num_rows() > 0)
{
$return = $query->result_array();
return $return;
}
else return false;
}
the reason I am having trouble is that as it is at return $return; returns the correct number of results but only displays the word "array". then if i change it to return $return[0]; returns the first entry of information correctly.
So what i want to be able to do is select all array numbers e.g return $return[*]; if only was possible.
Any suggestions would be much appreciated.
return $return; is the correct way to return an array from this function, but you can't just echo() the return value, since it's an array. When you try to echo an array, you get just the literal word "Array" (this also raises a notice which you would've seen with error reporting turned on).
You have to iterate over it and print each array element out, or use implode():
$array = $obj->get_audit_message($productId,$accountId); // However you call it
echo implode( "<br />\n", $array) . "<br />\n";
Or:
$array = $obj->get_audit_message($productId,$accountId); // However you call it
foreach( $array as $el) {
echo $el . "<br />\n";
}
Both of the above snippets will produce the exact same output.
There is several easy ways to display content of PHP Array in HTML.
The most simple is to view it via print_r command like this:
print_r ($my_array);
If you need to be "nice" formatted, add PRE tag like this:
echo "<pre>";
print_r($my_array);
echo "</pre>";
or like this:
echo "<pre>".print_r($my_array, 1)."</pre>";
Also, there is similar var_dump and var_export PHP function:
echo "<pre>";
var_dump($my_array);
echo "</pre>";
or
echo "<pre>";
var_export($my_array);
echo "</pre>";
Just choose your preferred stile.
I am updating my question with a few breakthroughs i was able to achieve today. I used get_object_vars.
This code was able to print out the value i am trying to iterate over.
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
print_r('<pre>'. print_r($arrayPid) .'</pre>');
This http://www.image-share.com/ijpg-1163-165.html is what i saw as a result.
Now since this Object has objects inside it along with the values i need i.e. FileID,FileName etc. I am seeing the error message but a glimpse of the output. The code i used was this (just a very minor change from the above. I used a foreach)
$fileStatus = $ServicesLink->GetFileStatus(array('Ticket'=>$ticket,'ProjectID'=>$pidobtained,'SourceLanguageID'=> "", 'TargetLanguageID'=> "",'FileID'=> "",'Filename'=>""));
$arrayPid = array();
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//$arrayPid =$fileStatusObtained ;
}
echo is_array($arrayPid) ? 'Array' : 'not an Array';
echo "<br>";
echo("Count of array ".count($arrayPid));
echo "<br>";
//print_r('<pre>'. print_r($arrayPid) .'</pre>');
foreach($arrayPid as $val) {
echo ($val);
echo "<br>";
}
}
As a result of this i saw the following output http://www.image-share.com/ijpg-1163-166.html .
The index number 1 occupies the object and hence the error for string conversion.
If i use a For loop instead of the foreach in the code just above,i am unable to print the values.
I tried:
for($i=0;$i<(count($arrayPid));$i+=1)
{
echo($arrayPid[$i]);
}
But this would print nothing.
Could any one help me with a way so that i can iterate and have the values inside that array $arrayPid.
Would like to have your suggestions, views, doubts on the same.
I am sorry that i am using imageshare but that is the only way i can share my screens.
Thanks
Angie
The correct way to use it is:
foreach($fileStatus->GetFileStatusResult->FileStatuses->FileStatus as $fileStatusObtained)
{
$arrayPid = get_object_vars($fileStatusObtained);
//print_r($fileStatusObtained->FileID);
$fileId [] = $fileStatusObtained->FileID;
...
}