我有一个像下面这样的数组:
$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()函数来实现这一点时,我一直没有成功。查找数组中相邻元素的最简单方法是什么?(如果我在“艺术家”页面,我将如何链接到“射箭”和“羽毛球”。)
发布于 2015-10-04 01:41:05
您可以遍历数组以找到当前键,然后再遍历一个元素。一个经过测试的例子:
$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 (如果未找到当前项,或者我们位于数组的最开始/末尾,并且没有可用的上一项/下一项)。
https://stackoverflow.com/questions/32925134
复制相似问题