我如何从这个数组中获取$ userid和$ username的所有值
a:1:{s:2:"cc";a:2:{i:4;s:4:"koko";i:8;s:4:"soso";}}
我的代码只打印最后一个字符串,我希望将所有值作为数组,并在循环中打印所有值
$touser = array();
$sql = $db->query_read("SELECT touserarray FROM " . TABLE_PREFIX . " pmtext where pmtextid = 147 ");
while ($sql1 = $db->fetch_array($sql))
{
$touser = unserialize($sql1['touserarray']);
foreach($touser AS $key => $item)
{
if (is_array($item))
{
foreach($item AS $subkey => $subitem)
{
$username = $subitem;
$userid = $subkey;
}
}
else
{
$username = $item;
$userid = $key[$i];
}
}
}
echo $username .'<br />'. $userid ;
当我打印$ username和$ userid时
只打印姓氏和最后一个ID
//输出
用户名:soso
userid:8
答案 0 :(得分:0)
您没有在任何地方保存值,因此userid
和username
每次都会覆盖。
试试这个:
<?php
$touser = array();
$sql = $db->query_read("SELECT touserarray FROM " . TABLE_PREFIX . " pmtext
where pmtextid = 147 ");
while ($sql1 = $db->fetch_array($sql)) {
$touser = unserialize($sql1['touserarray']);
foreach($touser AS $key => $item) {
if (is_array($item)) {
foreach($item AS $subkey => $subitem) {
$username = $subitem;
$userid = $subkey;
echo $userid . '/' . $username;
}
}
else {
$username = $item;
$userid = $key;
echo $userid . '/' . $username;
}
}
}
?>
答案 1 :(得分:0)
如果要打印或存储数据,则需要为其创建新的数据结构。如果您只想打印数据,则需要在设置$username
和$userid
的循环中执行此操作;否则每次循环运行时都会覆盖这些值。
# create an array for storing user names and IDs.
$user_arr = array();
foreach($touser as $key => $item)
{
if (is_array($item))
{
foreach($item AS $subkey => $subitem)
{
$username = $subitem;
$userid = $subkey;
}
}
else
{
$username = $item;
$userid = $key[$i];
}
# store the data as $user_arr[$id] = $name
$user_arr[$userid] = $username;
# or if you just want to print off the data during the loop...
echo "ID: $userid; name: $username" . PHP_EOL;
}
foreach ($user_arr as $k => $v) {
echo "id: $k; name: $v" . PHP_EOL;
}
输出:
id: 4; name: koko
id: 8; name: soso
答案 2 :(得分:0)
您的序列化数组具有以下形式:
array(1) {
'cc' =>
array(2) {
[4] =>
string(4) "koko"
[8] =>
string(4) "soso"
}
}
你需要再迭代一次(itemCC为&#34; cc&#34;键):
foreach ($touser as $itemCC) {
foreach ($itemCC AS $key => $item) {
if (is_array($item)) {
foreach ($item AS $subkey => $subitem) {
$username = $subitem;
$userid = $subkey;
}
} else {
$username = $item;
$userid = $key;
}
$result[$userid] = $username;
}
}
// print result
foreach ($result as $userId => $username) {
echo $userId . " " . $username . "<br />\n";
}
例如,$ result变量是此形式的数组userid =&gt; $用户名。