首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在多维PHP数组中获取next()?

如何在多维PHP数组中获取next()?
EN

Stack Overflow用户
提问于 2015-10-04 00:59:42
回答 5查看 57关注 0票数 1

我有一个像下面这样的数组:

代码语言:javascript
运行
复制
$products = array();

$products["Archery"] = array(
    "name" => "Archery",
    "img" => "img/wire/100-Archery.jpg",
    "desc" => "Archer aiming to shoot",
    "prices" => array($price1,$price3),
    "paypal" => $paypal2,
    "sizes" => array($size1, $size2)
);
$products["Artist"] = array(
    "name" => "Artist",
    "img" => "img/wire/101-Artist.jpg",
    "desc" => "Artist with palette & easel",
    "prices" => array($price3,$price6),
    "paypal" => $paypal5,
    "sizes" => array($size1, $size2)
);
$products["Badminton"] = array(
    "name" => "Badminton",
    "img" => "img/wire/102-Badminton.jpg",
    "desc" => "About to hit bird above head",
    "prices" => array($price1,$price3),
    "paypal" => $paypal2,
    "sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Stance"] = array(
    "name" => "BASEBALL -Bat - Stance",
    "img" => "img/wire/103a-Baseball-Stance.jpg",
    "desc" => "Waiting for pitch",
    "prices" => array($price1,$price3),
    "paypal" => $paypal2,
    "sizes" => array($size1, $size2)
);
$products["Baseball-Bat-Swing"] = array(
    "name" => "BASEBALL - Bat - Swing",
    "img" => "img/wire/103b-Baseball-Swing.jpg",
    "desc" => "Just hit ball",
    "prices" => array($price1,$price3),
    "paypal" => $paypal2,
    "sizes" => array($size1, $size2)
);

我有一个从这个数组中加载单个产品的页面,我正在尝试制作"prev“和"next”按钮,它们将链接到阵列中的相邻产品。我的PHP技能非常基础,在尝试使用prev()和next()函数来实现这一点时,我一直没有成功。查找数组中相邻元素的最简单方法是什么?(如果我在“艺术家”页面,我将如何链接到“射箭”和“羽毛球”。)

EN

Stack Overflow用户

发布于 2015-10-04 01:41:05

您可以遍历数组以找到当前键,然后再遍历一个元素。一个经过测试的例子:

代码语言:javascript
运行
复制
$current_page = 'Artist'; // as an example

$prev = $next = false; // the keys you're trying to find

$last = false; // store the value of the last iteration in case the next element matches

// flag if we've found the current element so that we can store the key on the next iteration
// we can't just use $last here because if the element is found on the first iteration it'll still be false
$found = false;

foreach ($products as $key => $value) {

    // if we found the current key in the previous iteration
    if ($found) {
        $next = $key;
        break; // no need to continue
    }

    // this is the current key
    if ($key == $current_page) {
        $found = true;
        $prev = $last;
    }

    $last = $key; // store this iteration's key for possible use in the next iteration
}

在此脚本的末尾,$prev和$next将包含上一项/下一项的键或为false (如果未找到当前项,或者我们位于数组的最开始/末尾,并且没有可用的上一项/下一项)。

票数 1
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32925134

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档