I have the following format:
{ "_id" : { "$oid" : "61f41a529210000060005487" }, "number" : "3", "name" : "Honduras", "description" : "1500m height farming, price per 200gr", "price" : 7, "stock" : 10, "stars" : "Rated with 4.0 stars by users." }
I need to parse a few entries like the above in PHP. I am using foreach for that purpose. Everything except {"_id": {"$oid": ... }} field seems to be parsed correctly. I get the following error:
Fatal error: Uncaught TypeError: Cannot access offset of type string on string
PHP script:
$products = json_encode($cursor['products']);
$products = json_decode($products, true) ;
foreach ($products as $product) {
$stringID = (string)$product['_id'];
echo '<tr>';
echo '<td>' . $stringID . '</td>';
echo '<td>' . $product['number'] . '</td>';
echo '<td>' . $product['name'] . '</td>';
echo '<td>' . $product['description'] . '</td>';
echo '<td>' . $product['price'] . '</td>';
echo '<td>' . $product['stock'] . '</td>';
echo '<td>' . $product['stars'] . '</td>';
echo '</tr>';
}
I have tried many solutions can't parse it though. Any suggestions?
$product is a string, not an object. You should json_decode($product) before to access to properties.
foreach ($products as $product)
{
$product = json_decode($product); // << decode here
$stringID = $product['_id']['$oid']; // << access to ID
// echo row :
echo '<tr>';
echo '<td>' . $stringID . '</td>';
echo '<td>' . $product['number'] . '</td>';
echo '<td>' . $product['name'] . '</td>';
echo '<td>' . $product['description'] . '</td>';
echo '<td>' . $product['price'] . '</td>';
echo '<td>' . $product['stock'] . '</td>';
echo '<td>' . $product['stars'] . '</td>';
echo '</tr>';
}
I am having two functions printBefore(json1) and printAfter(json2).
Both are having json object as parameter.jsons are coming from database. They are parsing json and displaying it in correct format.
But it is taking more than 30 seconds.
When I removed functon and displays json as it is. It is not taking time more than second.
I am not able isolate problem. Please Help.
foreach ($records as $record) {
echo '<tr>';
echo '<td>' . $userNames['users'][$record->uid] . '</td>';
echo '<td>' . $userNames['users'][$record->uid] . '</td>';
echo '<td>' . $record->val . '</td>';
echo '<td>' . $record->mi. '</td>';
echo '<td>' . $record->created_on . '</td>';
echo '<td>' . printBefore($record->newData) . '</td>';
echo '<td>' . printAfter($record->oldData) . '</td>';
echo '</tr>';
}
Code for printAfter($oldData)
$oldData = json_decode($oldData, true);
if (isset($OldData['sub_category'])) {
$str = $str . "|Category : " . $this->category[$OldData['sub_category']] . "|";
}
code for PrintBefore($newData)
$newData = json_decode($newData, true);
if (isset($newData['sub_category'])) {
$str = $str . "|Category : " . $this->category[$newData['sub_category']] . "|";
}
How can I properly do the the numbering of the results? What i did was
<?php
if($results)
{
$x = 1;
foreach ($results as $data)
{
echo '<tr>';
echo '<td>' . $x++. '</td>';
echo '<td>' . $data->item_id . '</td>';
echo '<td>' . $data->item_name . '</td>';
echo '<td>' . $data->item_category . '</td>';
echo '<td>' . $data->item_costprice . '</td>';
echo '<td>' . $data->item_retailprice . '</td>';
echo '<td>' . $data->item_tax . '%</td>';
echo '</tr>';
}
}
?>
But it has the same numbering per page.
The numbering starts with 1 because thats the value you assign to it before the loop starts.
Assuming you pass the page number to your controller your could do the following:
$x = count($results) * ($pagenumber-1);//use count or some other type of count method
This will make the $x value 1 on the first page, 31 on the second page, 61 on the third page etc...
Then inside the loop change $x++ to ++$x otherwise the first page will be counted from 0 to 29.
I'm trying to re-write this code so that it goes with the columns that are going to be user-defined. With this, my challenge consists of
a) Needs to select random starting item from array
b) Select the next random color from the original array that is not equivalent to the most recent items selected based the number: $intNotesColumn + 1
I was thinking a do-while statement nested inside another was appropriate for this but am unsure how to go about this. Here is my code so far:
$metroUIcolors = array( "#A30061", "#8200CC", "008987", "#A05000", "#B85A93", "#C07807", "#E51400", "#297A29" );
$metroUIcolorsLength = count($metroUIcolors);
$intNotesColumn = 3; // This will be user-defined later
// Now I query the SQL database to get my base-code
if ($result->num_rows > 0) {
// output data of each row
echo '<table border=0 valign=top>'
. '<tr>'
. '<td colspan=' . $intNotesColumn . '>' . '<h1>header</h1>' . '</td>'
. '</tr>'
. '<tr>';
$counterRank = 1;
while($row = $result->fetch_assoc()) {
echo "<td bgcolor=" . $metroUIcolors[rand(0, $metroUIcolorsLength - 1)]. ">"
. "<h2>" . $row["username"] . '</h2><br />'
. "<p class='notes'>" . $row["notes"] . "</p>"
. "<p class='footnotes'>"
. "<br />Last Reset: " . $row["lastReset"]
. '<br />Last Update: ' . $row['lastUpdate']
. '<br />SessionID: ' . $row["sessionID"]
. "<br />Counter = " . $counterRank . "</td>". '</p>';
if ($counterRank % $intNotesColumn == 0)
{
echo '</tr><tr>';
}
$counterRank++;
}
echo '</tr></table>';
} else{
echo "No Notes Found in databases";
}
Then, why don't you do it order picking one color at a time. You could use shuffle() so that there will be a different starting color everytime.
<?php
$counterRank = 1;
// shuffle the array
shuffle($metroUIcolors);
while($row = $result->fetch_assoc()) {
$rand_color = $counterRank % $metroUIcolorsLength;
echo "<td bgcolor=" . $metroUIcolors[$rand_color]. ">";
// everything else
$counterRank++;
}
?>
If you insist on doing the way you said, you may create an array $colorCount which has color codes as keys and count as values.
<?php
$counterRank = 1;
$colorCount = array_fill_keys($metroUIcolors, 0);
while($row = $result->fetch_assoc()) {
do {
$rand_color = $metroUIcolors[rand(0, $metroUIcolorsLength - 1)];
} while ($colorCount[$rand_color] > 5);
echo "<td bgcolor=" . $rand_color. ">";
// everything else
$counterRank++;
$colorCount[$rand_color] += 1;
}
?>
I have this bit of code which loops through an array and echos out the result to the page thus:
while($row = mysqli_fetch_array($result)) {
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' . $row['name'] . '</a></td>' . '<td>' . $row['provider'] . '</td>' . '<td>' . $row['media'] . "</td></tr><br />\n";
}
It works just fine, but I was hoping to use an 'if' statement on the $row['media'] because it contains some NULL and some !NULL results.
I wanted to be able to echo a different response a little like:
if ($row['media'] != NULL){
echo 'Nope';
} else {
echo $row['media'];
}
Is this possible in this situation?
Thanks.
use:
if ( is_null( $row['media'] ) ) { ... } else { ... }
The best way to accomplish this is using ternary operators:
while (whatever)
{
echo 'foo'
.($statement ? 'bar' : '')
.'baz';
}
Yeah, you would just end the echo, perform the if statement, and then use another echo to finish the code off. When it is parsed, the HTML will still be usable.
while($row = mysqli_fetch_array($result)) {
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' . $row['name'] . '</a></td>' . '<td>' . $row['provider'] . '</td>' . '<td>';
if($row['media'] == NULL) { echo 'Nope'; } else { echo $row['media']}
echo "</td></tr><br />\n";
}
Well, a very simple solution would be to do this...
$media = $row['media'];
if ($row['media'] == NULL)
$media = 'nope';
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' .$row['name']. '</a></td>';
echo '<td>' . $row['provider'] . '</td>' . '<td>' . $media . "</td></tr><br />\n";
Yes, break your echo into two different echos:
echo "<tr><td><a target="_blank" href="'" ; // (etc etc)
if($row['media'] != NULL) {
echo "NOPE";
} else {
echo $row['media'];
}
echo " $row['url'] . '">'; // (etc etc)
The syntax isn't perfect but I'm pretty sure you'll get the idea :)
If I understand your question then this should work just fine:
if(is_null($row['media']) echo($row['media']) else echo('Nope');
you can always just use another variable and set it before your echo statement, then use that variable in your echo statement. if you want a one-liner, you can use shorthand syntax like this:
($row['media'] != null) ? 'Nope' : $row['media']
and insert that where you currently just have $row['media']
Why not do it this way?
while($row = mysqli_fetch_array($result)) {
$media = ($row['media'] != NULL) ? $row['media'] : "Invalid";
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' . $row['name'] . '</a></td>' . '<td>' . $row['provider'] . '</td>' . '<td>' . $media . "</td></tr><br />\n";
}
Have the value put into a temp variable before the echo:
$mediaVal = $row['media'];
if ($mediaVal == NULL) $mediaVal = 'Nope';
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' . $row['name'] . '</a></td>' . '<td>' . $row['provider'] . '</td>' . '<td>' . $mediaVal . "</td></tr><br />\n";
You might consider stripping each field out into a dedicated variable incase you would life to process them in a similar manner etc
You can do something like this in your select statement
select
CASE
WHEN media IS NULL THEN 'Nope';
ELSE media
END as media
from
table
where......
read more : link text
Yes you can do that. You might want to break the echo into multiple echos so its a little easier to see whats going on.
Also, you should check over your if statement. Be careful with your conditionals.
if ($row['media'] != NULL) {
echo 'Nope';
} else {
echo $row['media'];
}
That will output 'Nope' if $row['media'] is not null. I assume you want to output 'Nope' if $row['media'] is null. In that case you want to use == instead of !=.
You can put it in one statement:
while ( $row = mysqli_fetch_array($result) ) {
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' . $row['name'] . '</a></td>' .
'<td>' . $row['provider'] . '</td>' .
'<td>' . (is_null($row['media'])?"Invalid Value":$row['media']) . "</td></tr><br />\n";
}
while($row = mysqli_fetch_array($result)) {
echo '<tr><td><a target="_blank" href="' . $row['url'] . '">' .
$row['name'] . '</a></td>' . '<td>' . $row['provider'] .
'</td>' . '<td>' .
($row['media'] == NULL ? 'Not Assigned' : $row['media']).
"</td></tr><br />\n";
}