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

问题描述 投票:0回答:2

我有一个数组,但键/索引的所有值仅显示零,而不是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>';
    }
}
php arrays multidimensional-array
2个回答
0
投票

您总是在数组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>';
    }
}

0
投票

我认为您正在寻找类似的东西:

 foreach($social_media as $social){

    $typesocial = $social['type'];
    if($social['type'] === 'social network') {
      $val[] = $social['url']['resource'];
    }

}
print_r($val);
© www.soinside.com 2019 - 2024. All rights reserved.