我从数组中得到数据库的响应,如下所示:
Array ( [mage_form_post_status] => draft [mage_form_post_type] => post [mage_form_post_permission] => public [mage_form_post_author] => 1 [mage_form_post_redirect] => 0 )
Array ( [mage_form_post_status] => draft [mage_form_post_type] => post [mage_form_post_permission] => public [mage_form_post_author] => 1 [mage_form_post_redirect] => 88 )
Array ( [mage_gym_name] => Fanna - test [mage_your_name] => John )
我想要实现的是仅显示mage_gym_name值。 我已成功使用此代码显示它:
foreach($gym_titles as $gym_title){
print_r(unserialize($gym_title));
echo '<br><br><br>';
}
问题是当没有结果时,就像在前两个数组中一样,我得到3个空的分界线。
所以我相信我应该包装:
print_r(unserialize($gym_title));
echo '<br><br><br>';
在某种情况下应检查当前数组是否包含该键名。
我尝试过这样但它不起作用:
foreach($gym_titles as $gym_title){
if (array_key_exists('mage_gym_name', $gym_title) {
echo "The 'first' element is in the array";
print_r(unserialize($gym_title));
echo '<br><br><br>';
} else {
echo 'no such element in this array';
}
}
答案 0 :(得分:0)
在检查密钥之前,您需要unserialize()
:
foreach($gym_titles as $gym_title){
$result = unserialize($gym_title);
if(isset($result['mage_gym_name'])) {
echo "The 'first' element is in the array";
print_r($result);
echo '<br><br><br>';
} else {
echo 'no such element in this array';
}
}
我使用isset()
,如果必须,请随时使用array_key_exists()
。