开发者

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

开发者 https://www.devze.com 2023-03-31 13:03 出处:网络
i insert in database values (array) with use function serialize(), how can echo they with unserialize() in tag &开发者_运维技巧lt;ul><li>...?

i insert in database values (array) with use function serialize(), how can echo they with unserialize() in tag &开发者_运维技巧lt;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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号