unserialize() value insert with serialize() of database.? - php

i insert in database values (array) with use function serialize(), how can echo they with unserialize() in tag <ul><li>...?
i have in database this: a:6:{i:0;s:15:"Coffee";i:1;s:14:"Satellite";i:2;s:11:"Game Notes";i:3;s:14:"Internet";i:4;s:10:"Pool";i:5;s:0:"";}
LIKE:
Coffee
Game Notes
Internet
Pool

You need to use unserialize(), as you said, with a foreach() loop, like this:
$arr = unserialize($dbString);
echo "<ul>";
foreach($arr as $key => $val)
{
echo "<li>$val</li>";
}
echo "</ul>";
This will echo a list containing value because foreach() iterates through the unserialize()d array, as you have specified in your question.
The $key => $part is the icing on the cake for foreach(); if you want the get the array key, simply reference $key. If you want the data for that key, use $val.
If you want to echo just one element (your example is Internet), just don't use a loop and reference it by key (integer):
$arr = unserialize($dbString);
echo $arr[2];
This echos the third element in the array on it's own.

Original question
Unserialize the data and loop over it printing it out. Notice that I have also added in checks to see that we are getting back an array and that it contains something before looping over it.
$data = unserialize($row['like']);
if(is_array($data) and count($data)) {
echo '<ul>';
foreach($like as $value) {
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
Internet
I think this is what you are asking for. To only echo out the value if its Internet.
$data = unserialize($row['like']);
if(is_array($data) and count($data)) {
echo '<ul>';
foreach($like as $value) {
if('Internet' != $value) {
continue;
}
echo '<li>' . $value . '</li>';
}
echo '</ul>';
}
JSON
If you can I would stop using serialize and use json_encode instead. It is easier to encode and decode in more programming languages and it is easier to edit by humans should you need to update the DB directly.

Related

How to get keys and values separately

(please don't say this is a duplicate, I checked here first )
I have a json file like this
[{"studentName":"ali","studentPhone":"123"},
{"studentName":"veli","studentPhone":"134"}
need to get keys and values separately I am trying something like this
foreach ($jsonArray as $array ) {
if(is_array($array)){
while($bar = each($array)){
echo $bar[1];
}
but gives me this output :
ali123veli134hatca134dursun13444
I have also tried this way :
if(is_array($array)){
foreach ($array as $key => $value) {
echo $value;
}
Make a try like this way with json_decode() or use array_column() to get only studentName
Using normal foreach:
<?php
$json = '[{"studentName":"ali","studentPhone":"123"}, {"studentName":"veli","studentPhone":"134"}]';
$array = json_decode($json,1); // the second params=1 makes json -> array
foreach($array as $key=>$value){
echo $value['studentName']."<br/>";
#echo $value['studentPhone']."<br/>";
}
?>
Using array_column():
<?php
$json = '[{"studentName":"ali","studentPhone":"123"}, {"studentName":"veli","studentPhone":"134"}]';
$array = json_decode($json,1);
$names = array_column($array,'studentName');
print '<pre>';
print_r($names); // to get only studentName
print '</pre>';
?>
First of all you need to decode the json string, assign it to a variable, then loop through that variable and echo out the names (studenName).
Ps: after decoding the JSON array we can acces the elements' names in each column using the -> notation, as we have objects stored in that array.
// decoding the json string
$jsonArray =
json_decode('[{"studentName":"ali","studentPhone":"123"},
{"studentName":"veli","studentPhone":"134"}]');
//loop through the array and print out the studentName
foreach($jsonArray as $obj) {
echo $obj->studentName . ' ';
// if you want to print the students phones, uncomment the next line.
//echo $obj->studentPhone . ' ';
}
// output: ali veli

Access Element in JSON data that doesn't have a standard name

I'm using the Kraken API to get a list of available currency pairings.
Here is the endpoint: https://api.kraken.com/0/public/AssetPairs
$kraken_coins =
file_get_contents('https://api.kraken.com/0/public/AssetPairs');
$kraken_coins = json_decode($kraken_coins, true);
foreach ($kraken_coins['result'] as $coin) {
echo $coin . "<br>";
}
I'm trying to extract the first element inside of "result", however each of these elements are named differently so I'm not sure how to target it. For example, the first two currency pairings returned are "BCHEUR" and "BCHUSD".
So with the loop I have above, it just echos "Array" repeatedly... not what I'm going for.
How do I target that element so I can loop through each one? Thanks!
Since, the json structure is:
You need to use:
foreach ($array as $key => $value) {
}
In this case:
foreach ($kraken_coins['result'] as $coin => $coindata) {
echo $coin . "<br>";
}

Parsing JSON in for each with increment PHP

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'];
}
}

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.

PHP : how to use foreach loop inside an echo statement?

i am tring to put a loop to echo a number inside an echo ;
and i tried as bellow :
$array = array();
$result = mysql_query("SHOW TABLES FROM `st_db_1`");
while($row = mysql_fetch_row($result) ){
$result_tb = mysql_query("SELECT id FROM $row[0] LIMIT 1");
$row_tb=mysql_fetch_array($result_tb);
$array[] = $row[0];
$array2[] = $row_tb[0];
//checking for availbility of result_tb
/* if (!$result_tb) {
echo "DB Error, could not list tablesn";
echo 'MySQL Error: ' . mysql_error();
exit;
} */
}
natsort($array);
natsort($array2);
foreach ($array as $item[0] ) {
echo "<a href=show_cls_db.php?id= foreach ($array2 as $item2[0]){echo \"$item2[0]\"}>{$item[0]}<br/><a/>" ;
}
but php is not considering foreach loop inside that echo ;
please suggest me something
As mentioned by others, you cannot do loops inside a string. What you are trying to do can be achieved like this:
foreach ($array as $element) {
echo "<a href='show_cls_db.php?id=" . implode('', $array2) . "'>{$element}</a><br/>";
}
implode(...) concatenates all values of the array, with a separator, which can be an empty string too.
Notes:
I think you want <br /> outside of <a>...</a>
I don't see why you would want to used $item[0] as a temporary storage for traverser array elements (hence renamed to $element)
Just use implode instead of trying to loop the array,
foreach ($array as $item)
{
echo implode("",$array2);
}
other wise if you need to do other logic for each variable then you can do something like so:
foreach ($array as $item)
{
echo '<a href="show_details.php?';
foreach($something as $something_else)
{
echo $something_else;
}
echo '">Value</a>';
}
we would have to see the contents of the variables to understand what your trying to do.
As a wild guess I would think your array look's like:
array(
id => value
)
And as you was trying to access [0] within the value produced by the initial foreach, you might be trying to get the key and value separate, try something like this:
foreach($array as $id => $value)
{
echo $id; //This should be the index
echo $value; //This should be the value
}
foreach ($array as $item ) {
echo "<a href=\"show_cls_db.php?id=";
foreach ($array2 as $item2) { echo $item2[0]; }
echo "\">{$item[0]}<br/><a/>" ;
}
No offense but this code is... rough. Post it on codereview.stackexchange.com for some help re-factoring it. A quick tip for now would be to use PDO, and at the least, escape your inputs.
Anyway, as the answers have pointed out, you have simply echoed out a string with the "foreach" code inside it. Take it out of the string. I would probably use implode as RobertPitt suggested. Consider sorting and selecting your data from your database more efficiently by having mysql do the sorting. Don't use as $item[0] as that makes absolutely no sense at all. Name your variables clearly. Additionally, your href tag is malformed - you may not see the correct results even when you pull the foreach loop out of the echo, as your browser may render it all away. Make sure to put those quotes where they should be.

Categories