【问题标题】:Storing values from nested array in new array将嵌套数组中的值存储在新数组中
【发布时间】:2015-10-26 02:35:10
【问题描述】:

好的,我是数组新手,这可能很简单,但我很难理解它。

我有一个简单的嵌套数组。我想做的是遍历所有值,只获取img url并将它们存储在一个单独的变量数组中。

我当前的代码可以找到 url,但不是很干净,也不是针对数组的 url 条目,而是简单地测试变量是否以“http”开头,以确定它是否是正确的条目。我想简单地从每个嵌套数组的第一项创建一个变量。

目前数组和代码的结构如下:

   Array
(
    [0] => Array
        (
            [0] => http://samplesite.com/img1.jpg
            [1] => 1000
            [2] => 667
            [3] => 
        )

    [1] => Array
        (
            [0] => http://samplesite.com/img2.jpg
            [1] => 1000
            [2] => 667
            [3] => 
        )

)

<?php foreach ($img_array AS $array) {
        foreach ($array AS $item) {
        //check to see if it is the URL entry else skip that part of array
            if (strpos($item, "http") === 0) {;?>
                <div>
                    <?php echo $item ?>
                </div>
    <?php 
    }
        } 
            }?>

我知道你可以用这种语句来定位嵌套数组:

foreach ($img_array AS $array => $item)

但是,当我使用它时,我只返回单词“array”而不返回任何值?

由于这些始终是嵌套数组的第一个值,我应该能够绕过使用 if 语句查找“http”以确定该值是否为 url。

我们的目标是提取所有 url 作为唯一变量,这些变量可用于从图像中生成幻灯片。

类似的东西。 foreach 循环在哪里生成单独的幻灯片代码。

<div class="item active">
  <img src="<?php $array[0] ?>" alt="alt" width="1000" height="400">
  <div class="carousel-caption">
    <p>Caption text here</p>
  </div>
</div>

<div class="item">
  <img src="<?php $array[1] ?>" alt="alt" width="1000" height="400">
  <div class="carousel-caption">
    <p>Caption text here</p>
  </div>
</div>

<div class="item">
  <img src="<?php $array[2] ?>" alt="alt" width="1000" height="400">
  <div class="carousel-caption">
    <p>Caption text here</p>
  </div>
</div>

感谢收看!

埃里克

【问题讨论】:

  • 图片 URL 是否总是在索引 0 处?

标签: php arrays foreach nested


【解决方案1】:

如果它始终是第一个值,您可以简单地访问嵌套数组中的第一个(索引为 0)字符串:

<?php foreach ($img_array AS $array) { ?>
            <div>
                <?php echo $array[0] ?>
            </div>
<?php } ?>

【讨论】:

  • 感谢您的快速回复,这很好!我使用的是 $array[$item] 而不是键号。
【解决方案2】:

只需使用 for 循环即可:

$img_urls = array();
for ($i = 0; $i < count($img_array); $i++) {
    $img_urls[$i] = $img_array[$i][0]; // since it is always the first element in the array
}

echo $img_urls[1]; // this will show the first image url

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-04
    • 2018-12-07
    • 2018-07-06
    • 1970-01-01
    • 2014-12-04
    • 2021-06-25
    • 1970-01-01
    • 2021-10-14
    相关资源
    最近更新 更多