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>";
}
Related
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.
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];
}
I have two arrays built from an XML response to an api. One array gives me the product info form one store and the other array gives me just the stock level in another. It looks like this:
foreach($filteredStock as $t=>$k){
$codeFirst[] = $k['code'];
echo '<tr><td>'.$t;
echo '</td><td>'.$k['desc'];
echo '</td><td>'.$k['family'];
echo '</td><td>'.$_POST['filterSelect'];
echo '</td><td>'.$k['onOrder'];
echo '</td><td>'.$k['cost'];
echo '</td><td>'.$k['sell'];
echo '</td><td>'.$k['invStore'];
echo '</td>';
}
$output = array();
$result = array_intersect_key($mainArray, array_flip($codeFirst));
foreach($result as $results=>$rValues){
echo '<td>'.$rValues['inv'];
echo '</td>';
echo '</tr>';
}
I want to display it so that it looks like this in the table:
code / desc / family / filteredClass / onOrder / cost / sell / invStore / invwarehouse
Because I need the second foreach loop to grab the values of the second array it causes a problem trying to get it to repeat on each line with the other array. Any suggestions?
Rather than echoing output each time the loop iterates, why don't you build up the table how you want it and then output it when you have it arranged properly?
It's not clear to me from the code exactly what you are trying to do, but if it's an organisation problem then why don't you store the values in seperate arrays and then combine then and arrange them appropriately before outputting them?
Using echo immediately for each loop iteration limits your options somewhat.
When sending data from a form to a second page, the value of the session is always with the name "Array" insteed of the expected number.
The data should get displayed in a table, but insteed of example 1, 2, 3 , 4 i get : Array, Array, Array.
(A 2-Dimensional Table is used)
Is the following code below a proper way to "call" upon the stored values on the 2nd page from the array ?
$test1 = $_SESSION["table"][0];
$test2 = $_SESSION["table"][1];
$test3 = $_SESSION["table"][2];
$test4 = $_SESSION["table"][3];
$test5 = $_SESSION["table"][4];
What exactly is this, and how can i fix this?
Is it some sort of override that needs to happen?
Best Regards.
You don't need any sort of override. The script is printing "Array" rather than a value, because you're trying to print to the screen a whole array, rather than a value within an array for example:
$some_array = array('0','1','2','3');
echo $some_array; //this will print out "Array"
echo $some_array[0]; //this will print "0"
print_r($some_array); //this will list all values within the array. Try it out!
print_r() is not useful for production code, because its ugly; however, for testing purposes it can keep you from pulling your hair out over nested arrays.
It's perfectly fine to access elements in your array by index: $some_array[2]
if you want it in a table you might do something like this:
<table>
<tr>
for($i = 0 ; $i < count($some_array) ; $i++) {
echo '<td>'.$some_array[$i].'</td>';
}
</tr>
</table>
As noted, try
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
That should show you what's in the session array.
A 2-dimensional table is just an array of arrays.
So, by pulling out $_SESSION["table"][0], you're pulling out an array that represents the first row of the table.
If you want a specific value from that table, you need to pass the second index, too. i.e. $_SESSION["table"][0][0]
Or you could just be lazy and do $table = $_SESSION["table"]; at which point $table would be your normal table again.
A nice way ...
<?php
foreach ($_SESSION as $key => $value) {
echo $key . " => " . $value . "<br>";
}
?>
Is it possible to echo or print the entire contents of an array without specifying which part of the array?
The scenario: I am trying to echo everything from:
while($row = mysql_fetch_array($result)){
echo $row['id'];
}
Without specifying "id" and instead outputting the complete contents of the array.
If you want to format the output on your own, simply add another loop (foreach) to iterate through the contents of the current row:
while ($row = mysql_fetch_array($result)) {
foreach ($row as $columnName => $columnData) {
echo 'Column name: ' . $columnName . ' Column data: ' . $columnData . '<br />';
}
}
Or if you don't care about the formatting, use the print_r function recommended in the previous answers.
while ($row = mysql_fetch_array($result)) {
echo '<pre>';
print_r ($row);
echo '</pre>';
}
print_r() prints only the keys and values of the array, opposed to var_dump() whichs also prints the types of the data in the array, i.e. String, int, double, and so on. If you do care about the data types - use var_dump() over print_r().
For nice & readable results, use this:
function printVar($var) {
echo '<pre>';
var_dump($var);
echo '</pre>';
}
The above function will preserve the original formatting, making it (more)readable in a web browser.
var_dump() can do this.
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
http://php.net/manual/en/function.var-dump.php
I think you are looking for print_r which will print out the array as text. You can't control the formatting though, it's more for debugging. If you want cool formatting you'll need to do it manually.
This is a little function I use all the time its handy if you are debugging arrays. Its pretty much the same thing Darryl and Karim posted. I just added a parameter title so you have some debug info as what array you are printing. it also checks if you have supplied it with a valid array and lets you know if you didn't.
function print_array($title,$array){
if(is_array($array)){
echo $title."<br/>".
"||---------------------------------||<br/>".
"<pre>";
print_r($array);
echo "</pre>".
"END ".$title."<br/>".
"||---------------------------------||<br/>";
}else{
echo $title." is not an array.";
}
}
Basic usage:
//your array
$array = array('cat','dog','bird','mouse','fish','gerbil');
//usage
print_array("PETS", $array);
Results:
PETS
||---------------------------------||
Array
(
[0] => cat
[1] => dog
[2] => bird
[3] => mouse
[4] => fish
[5] => gerbil
)
END PETS
||---------------------------------||
You can use print_r to get human-readable output.
See http://www.php.net/print_r
Similar to karim's, but with print_r which has a much small output and I find is usually all you need:
function PrintR($var) {
echo '<pre>';
print_r($var);
echo '</pre>';
}
//#parram $data-array,$d-if true then die by default it is false
//#author Your name
function p($data,$d = false){
echo "<pre>";
print_r($data);
echo "</pre>";
if($d == TRUE){
die();
}
} // END OF FUNCTION
Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function
In your case you can use in this way....
while($row = mysql_fetch_array($result)){
p($row); // Use this function if you use above function in your page.
}
You can use print_r to get human-readable output.
But to display it as text we add echo '<pre>';
echo '<pre>';
print_r($row);