Retrieve content from parsed json array - php

I have the following code that I need to be able to get each section of the array separately.
Here is the code:
$parsed = $parsed_json['forecast']['txt_forecast']['forecastday'];
foreach($parsed as $key => $value)
{
echo '<table border="1" width="200px">';
echo '<td>';
echo '<td><b>' . $value['title'] . '</td></font>';
echo '</tr>';
echo '<tr>';
echo '<tr>' .$value['fcttext'] . '</tr></font>';
echo '<td><img src=' . $value['icon_url'] . '></td>';
echo '</tr></table>';
}
What I want is to be able to get lets say the first title in the array
echo $value['title'][1]
The above is what i thought would work. But it returns just a single letter.
It should read "Saturday"
How can i go about getting it corrected?

$parsed[0]['title']; will return the first item of the array's title.
Indexing starts with 0 and not 1 (so 0 is first, 1 is second etc) - saving those bytes adds up on large projects!
As #JimL indicates, [1] gets the second item of our variable. If it's an array this is the second item of the array. As this is a string (the title) we get the second letter instead. Hope that explains it for you.

Related

Grab the last iteration of a foreach loop (where the last iteration needs to differ)

Is there a way I can determine the last iteration of a foreach loop, and implement some different code?
I'm trying to iterate through an array and output parts of it into a table.
Here is an example of my array:
array(2) {
[0]=> array(3) {
[date]=> string(10) "2013-09-18"
[title]=> string(75) "Ready For Retina HD: Create Pixel-Perfect Assets For Multiple Scale Factors"
[filepath]=> string(74) "ready-for-retina-hd-create-pixel-perfect-assets-for-multiple-scale-factors"
}
[1]=> array(3) {
[date]=> string(10) "2010-10-20"
[title]=> string(40) "Taking A Closer Look At Tech Conferences"
[filepath]=> string(40) "taking-a-closer-look-at-tech-conferences"
}
}
For each part, I want to output the title, then I want to output the filepath as a link, in two different places (once is a "view" link and the other is an "edit" link).
I need to run through the array and make each of these three items into a table row, so I've implemented a counter which inserts </tr><tr>every 3 items, to cut off the old row and start a new one.
It works great the only problem is in the case of the last item, because it will always open a new row due to the last <tr>
How can I restructure this so that it doesn't open the row on the last count?
echo "<table border='2'><tbody><tr>";
foreach ($myarray as $post){
// Adds to count, outputs title
echo "<td>" . $post['title'] . "</td>";
$rowcounter++;
// Adds to count, outputs filepath with "view"
echo "<td><a href='../posts/post-" . $post['filepath'] . "'>View</a></td>";
$rowcounter++;
// Adds to count, outputs filepath with "edit"
echo "<td><a href='../posts/post-" . $post['filepath'] . "?edit=true'>Edit</a></td>";
$rowcounter++;
// Tests the count
echo 'rowcounter = ' . $rowcounter;
if ($rowcounter == "3"){
$rowcounter = 0;
echo "</tr><tr>";
}
}
echo "</tr></tbody></table>";
Render your <tr>s only inside your loop, rather than opening and closing before and after, respectively.
As far as I can tell, there's no need for you to keep count of your 'rows' (which by the way are columns). You iterate for each row so all of your per-row markup should come between your foreach curly braces:
echo "<table border='2'><tbody>";
foreach ($myarray as $post){ // One iteration per row
echo '<tr>'; // Row STARTS here.
echo "<td>" . $post['title'] . "</td>";
echo "<td><a href='../posts/post-" . $post['filepath'] . "'>View</a></td>";
echo "<td><a href='../posts/post-" . $post['filepath'] . "?edit=true'>Edit</a></td>";
echo '</tr>'; // Row ENDS here.
}
echo "</tbody></table>";
I recommend George's answer for this but for future reference you could alternatively either use a for loop instead of a foreach:
foreach ($i=0; $i < count($myarray); $i++){
$post = $myarray[$i];
...
then check $i against the count of $myarray
or you could add a row count to the loop which increments on each iteration and do a check against the number of rows in $myarray

Unserialize query (array) data is not working

I gave recently created a search function with checkboxes that queries for the submitted checkbox values and returns those values into a table.
The problem however is that certain of the checkbox values (in the database) are serialized. When i display the query result variable in a foreach for every checkbox value, it returns serialized characters. Obviously i want to just show the string without the weird characters.
The original piece of code, where the entire serialized characters are returned was as follows:
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo"<td>" . $value . "</td>";
}
echo "</tr>";
}
}
echo '</table>';
So to just display the string of the database value i try'd to use the unserialize function (the $tmp is by the way the variable in which the query results are being stored). There were however several issues with this, namely:
echo doesnt work with unserialize
the database and query can also return non-serialized data (so the $tmp variable can contain a. serialized values with the weird characters and b. just a non-serialized normal string).
Because the unserialize function also gets the 'normal' strings, those normals trings will be outputted as blanks..
For some reason, the output of the arrays/unserialized data (with print_r) displays not the string but rather the entire array name, like this: Array ( [0] => [1] => Netherlands ).
The code below is how i try'd to unserialize the data:
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo "<td>";
$b=unserialize($value);
print_r($b);
echo "</td>";
}
echo "</tr>";
}
}
echo '</table>';
Though, like said before, the above code shows the entire array name and the 'normal' strings of the database that are also queried are displayed as blanks.
So what to do to get this fixed?
Thank you in advance
Php unserialize can return several things including an array which is your case. Do this
foreach($tmp[$i] as $key=>$value){
echo "<td>";
$b=unserialize($value);
if(is_array($b)){
//this assumes your array is always like this Array ( [0] => [1] => Netherlands )
echo $b[1];
}
else{
echo $value;
}
echo "</td>";
}

PHP Arrays and Form Values

PHP noob here. I am using PHP to present a supply order form. The list of supplies that can be ordered are dynamic, so I'm pulling them from a MySQL database. Here is the PHP code that is generating the HTML form fields by looping through the results of the query:
while($row = mysqli_fetch_array($itemresult))
{
echo "<input type='hidden' name='Item_ID[]' value='" . $row['Item_ID'] . "'></TD>";
echo "<TR><TD class='itemdesc'>" . $row['Item_Name'] . " </TD>";
echo "<input type='hidden' name='Item_Name[]' value='" . $row['Item_Name'] . "'></TD>";
echo "<TD>" . $row['Item_Qty'] . " </TD>";
echo "<TD class='itemprice'>" . $row['Price'] . " </TD>";
echo "<input type='hidden' name='Item_Price[]' value='" . $row['Price'] . "'></TD>";
echo "<TD><input type='text' size='3' name='Order_Qty[]'></TD>";
echo "<TD><input type='checkbox' name='Off_Day[]'></TD>";
}
I have no experience using arrays, however it makes sense that I need these form values passed to my process.php file in an array format. For now, the purpose of my process.php is to simply print a list of Item_Name and the associated Order_Qty by themselves, pretty much like:
Pencils 10
Pens 7
and on and on.
Being new to arrays and PHP, I have no idea how to accomplish this in my process.php files and would appreciate some guidance. Thanks!
+++++++++++++++++++++++++++++++++++++++++++++++
*#yknivag*
Thank you! That helps me understand me the structure. I've been testing various foreach examples online, am hitting a roadblock and could use some additional help. My array result looks like this.
[Item_Name] => Array (
[0] => One Item
[1] => Second Item
[2] => Third Item
[3] => Fourth Item )
[Item_Price] => Array (
[0] => 0.00
[1] => 64.50
[2] => 110.00
[3] => 38.45 )
How do I reference a particular value in the array, such as 'Second Item'? I can't seem to figure out the syntax for referencing a particular item. For instance, this statement returns no data.
echo "Item: " . $_POST[Item_Name] . "<BR>";
What would also be helpful, is to know how to display corresponding array items such as 'Second Item' and '64.50' together?
The following foreach loop seems like it should do the trick, however it doesn't return any data either.
foreach ($myarray as $key => $value)
{
echo "<p>".$key." ".$value."</p>";
}
Everything I've read says this should give me what I want, and I'm confused as to why it's returning nothing.
In your process.php file begin with:
<?php
print "<pre>" . PHP_EOL;
print_r($_POST);
print "</pre>" . PHP_EOL;
?>
Then you will see the structure of the data which is being sent back and that should help you to work out how to process it.
Once you have the structure, examine the foreach command.
You want an associative array
array("pencil" => 9.99, "pen" => 3.23, "paper" => 21.11)
If you are submitting your form through AJAX, you would use JavaScript to post the values to your PHP page.
var pencil = document.getElementById("pencil").value;
var pen = document.getElementById("pen").value;
var paper = document.getElementById("paper").value;
$.post("process.php", {pencil: pencil, pen: pen, paper: paper});
On your "process" page, you would grab the values that were posted
$pencil = $_POST["pencil"];
$pen = $_POST["pen"];
$paper = $_POST["paper"];
then build your array with the following
$myarray = array("pencil" => $pencil, "pen" => $pen, "paper" => $paper);
Edit
In your WHILE loop, build yourself an array by putting this at the end
$myarray[$name] = $price;
Then outside of the loop, encode your array into a JSON object
$myjson = json_encode($myarray, JSON_HEX_APOS);
Now that you have a JSON object, you'll need to grab it in JavaScript
var myjson = <?php echo $myjson; ?>;
Then you can do whatever you want with the key / value pairs
for(var key in myjson){
var item_name = key;
var item_price = myjson[key];
//where the magic happens
}

PHP Mutliarray Key and Value Print

$icecream = array (
"Choco" => array('2 Dollars'),
"Mango" => array('3 Dollars')
);
print $icecream[0][0];
expected output:
2 Dollars
Edit: I have a huge list of icecream sorts and i do want to use a loop to output all the information as a HTML DOM. So I do not want to go through each array value and echo it with the explicit value (i.e. 'Choco', 'Orange', etc...).
I want to use values as keys for the "first array level" ($icecream[0]),
It does output nothing at all. What is my logical flaw with this solution?
try this:
echo $icecream['Choco'][0]
Your problem here is calling the wrong key for the 1st dim
.
.
For your updated question, try this:
$ice_k = array_keys($icecream);
echo $icecream[$ice_k[0]][0];
You're not using the associative array right. You need to use the right key.
echo $icecream['choco'][0];
You can use position but it will be a counter like this:
$counter = 0;
foreach($icecream As $k=>$v) {
echo $icecream[$k][0] . ' [' . $counter . ']';
$counter++;
}
and if you want to get only value you can use previous code
$ice_k = array_keys($icecream);
$position = 5;
if( isset($ice_k[$position]) ) {
echo $icecream[$ice_k[$position]][0];
}

php - Omitting columns in an array, with in another array

This is a fun one.
I have a function that produces an array from mySQL...or better yet, it produces an array of arrays. Follow?
I've figured out how to drill down in to the array to display them into a working table. As so:
<table id="list_table" cellpadding="1" cellspacing="1">
<?php
$array = $this->disparray;
foreach($array as $key => $value)
{
echo '<tr>';
foreach($value as $key => $value)
{
echo '<td>' . $value . '</td>';
}
echo '</tr>';
}
?>
</table>
HOWEVER, I only want to call specific <td>'s, which means, I have to call references to the specific column indexes. I've tried $value['1'], but it just does some crazy stuff. so, where I'm stuck is I do not know where to call the specific column indexes that I want.
You're nesting/overwriting your $key and $value variables. That is likely completely messing things up.
Try:
<?php
$array = $this->disparray;
foreach($array as $key => $value)
{
echo '<tr>';
foreach($value as $k => $v)
{
echo '<td>' . $v . '</td>';
}
echo '</tr>';
}
?>
That might help you solve your issues.
You stated " I have to call references to the specific column indexes" and "I just need to know how to specify which columns to use. (or which indexes/keys to display)".
I suspect your issue is actually more involved than this, but the answer to that question is to use the standard syntax for multidimensional arrays. E.g., $array['index1']['index2'].
More information about the PHP array syntax is here. Please clarify your question if you need more information.

Categories