我有多维数组,如下所示:
Array
(
[0] => Array
(
[banner_link] => http://www.eclipse-pos.com/eclipse/images/small_banner2.jpg
)
[1] => Array
(
[banners] => 143038313801.jpg,143038313809.jpg,143038313811.jpg
)
[2] => Array
(
[banners] => 143038306301.jpg,143038306302.jpg,143038306303.jpeg,143038306310.jpg,143038306311.jpg,143038306312.png
)
)
现在我想将banner_link
键重命名为banners
。
Array
(
[0] => Array
(
[banners] => http://www.eclipse-pos.com/eclipse/images/small_banner2.jpg
)
[1] => Array
(
[banners] => 143038313801.jpg,143038313809.jpg,143038313811.jpg
)
[2] => Array
(
[banners] => 143038306301.jpg,143038306302.jpg,143038306303.jpeg,143038306310.jpg,143038306311.jpg,143038306312.png
)
)
我试过用波纹管代码但没有运气。
foreach ( $getBefamousHomepage as $k=>$v )
{
$getBefamousHomepage[$k] ['banners'] = $getBefamousHomepage[$k] ['banner_link'];
unset($getBefamousHomepage[$k]['banner_link']);
}
获取此错误:
Notice: Undefined index: banner_link in /var/www/sitename/application/views/_templates/global_footer.php on line 14
Notice: Undefined index: banner_link in /var/www/sitename/application/views/_templates/global_footer.php on line 14
Array
(
[0] => Array
(
[banners] => http://www.eclipse-pos.com/eclipse/images/small_banner2.jpg
)
[1] => Array
(
[banners] =>
)
[2] => Array
(
[banners] =>
)
)
我做错了什么?
感谢。
答案 0 :(得分:3)
banner_link
并不总是存在。使用isset()
查看是否存在
:
if(isset($getBefamousHomepage[$k]['banner_link'])) {
$getBefamousHomepage[$k]['banners'] = $getBefamousHomepage[$k]['banner_link'];
unset($getBefamousHomepage[$k]['banner_link']);
}
答案 1 :(得分:1)
您应该检查banner_link
是否存在。
为了避免覆盖banner
,您应该检查banner
是否已经存在。
foreach ( $getBefamousHomepage as $k=>$v ) {
if(isset($getBefamousHomepage[$k]['banner_link']) && !isset($getBefamousHomepage[$k]['banners'])) {
$getBefamousHomepage[$k]['banners'] = $getBefamousHomepage[$k]['banner_link'];
unset($getBefamousHomepage[$k]['banner_link']);
}
}
答案 2 :(得分:0)
你的代码几乎是好的。您只需添加额外的检查以查看banner_link是否存在 如果没有,它会抛出一个通知(如你所见),但代码仍将执行,因此“banner”索引将被设置为null。
代码示例:
foreach ( $getBefamousHomepage as $k=>$v )
{
if (isset($getBefamousHomepage[$k]['banner_link']))
{
$getBefamousHomepage[$k] ['banners'] = $getBefamousHomepage[$k] ['banner_link'];
unset($getBefamousHomepage[$k]['banner_link']);
}
}
答案 3 :(得分:0)
您阵列中的某些元素没有banner_link,并且在您尝试访问它时会引发警告。试试这个:
if(isset($getBefamousHomepage[$k] ['banner_link'])) {
$getBefamousHomepage[$k] = array("banners" => $getBefamousHomepage[$k] ['banner_link']);
}