提问者:小点点

如何向数组添加索引,而不是让键从零开始?


我有一个数组,但键/索引只显示所有值为零,而不是0,1,2,3,4,5。 当我打印数组时,它显示为

Array
(
    [0] => https://giphy.com/ladygaga
)
Array
(
    [0] => https://plus.google.com/+LadyGaga
)
Array
(
    [0] => https://twitter.com/ladygaga
)
Array
(
    [0] => https://www.facebook.com/ladygaga
)
Array
(
    [0] => https://www.instagram.com/ladygaga/
)

这是我的代码

foreach($social_media as $social){

    $typesocial = $social['type'];
    $val = array($social['url']['resource']);

    if ($social['type'] === 'social network') 
    {
        echo '<pre>'; print_r($val); echo '</pre>';
    }
}

共2个答案

匿名用户

我想你要找的是这样的东西:

 foreach($social_media as $social){

    $typesocial = $social['type'];
    $val[] = $social['url']['resource'];

}
print_r($val);

匿名用户

始终在数组array($social['url']['resource'])中赋值; 因此在索引0上显示一个值始终移除此数组尝试以下代码

 $val = array();
foreach($social_media as $social){

    $typesocial = $social['type'];
    $val[] = (isset($social['url']['resource'])) ? $social['url']['resource'] : '';

    if ($social['type'] === 'social network') 
    {
        echo '<pre>'; print_r($val); echo '</pre>';
    }
}