У меня есть массив, подобный приведенному ниже:
$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(). Какой самый простой способ найти соседние элементы в массиве? (Если я на странице "Исполнитель", как бы я ссылался на "Стрельба из лука" и "Бадминтон")
На основе данных массива вы можете использовать следующую функцию. Я использовал функцию array_keys(), чтобы создать массив только с ключами исходного массива, и вся работа выполняется с использованием нового массива.
function custom_array_pagination($data = array()) {
$current_page = 'Baseball-Bat-Swing'; //$current_page = $_GET['product']; //Change to this when you have set up your final code
$data_keys = array_keys($data); //This is the array all the work is done
$s = '';
if (!in_array($current_page, $data_keys)) { //If there is no such element as the $_GET element in the array
return $s;
}
$is_first = false;
$is_last = false;
$found_prev = false;
$found_next = false;
$next_text = '';
if ($current_page == $data_keys[0]) {
$is_first = true;
}
if ($current_page == end($data_keys)) {
$is_last = true;
}
$s .= '<ul class="pagination">';
if ($is_first) { //If it is the first element then show only text
$s .= '<li class="first">First'.'</li>';
} else {
$s .= '<li class="first"><a href="'.$data_keys[0].'">First</a>'.'</li>';
}
foreach($data_keys as $key => $value) {
if ($is_first && !$found_prev) { //If it is the first element then show only text
$found_prev = true;
$s .= '<li class="prev">Prev'.'</li>';
} else {
if (!$found_prev) { //If prev has not been found yet
$prev = $data_keys[array_search($current_page, $data_keys) - 1];
$found_prev = true;
$s .= '<li class="prev"><a href="'.$prev.'">Prev</a>'.'</li>';
}
}
if ($current_page == $value) {
$s .= '<li class="current">'.$data[$value]['name'].'</li>';
} else {
$s .= '<li class="current"><a href="'.$value.'">'.$data[$value]['name'].'</a>'.'</li>';
}
if ($is_last && !$found_next) { //If it is the last element then show only text
$found_next = true;
$next_text = '<li class="next">Next'.'</li>';
} else {
if (!$found_next) { //If next has not been found yet
if ($value == $data_keys[count($data_keys) - 1]) { //If this value is the last value in the table
$found_next = true;
$next = $data_keys[array_search($current_page, $data_keys) + 1];
$next_text = '<li class="next"><a href="'.$next.'">Next</a>'.'</li>';
}
}
}
}
$s .= $next_text;
if ($is_last) { //If it is the last element then show only text
$s .= '<li class="last">Last</li>';
} else {
$s .= '<li class="last"><a href="'.$data_keys[count($data_keys) - 1].'">Last</a>'.'</li>';
}
return $s;
}
Вы можете использовать эту функцию следующим образом:
echo custom_array_pagination($products);
Вы можете пересечь массив, чтобы найти текущий ключ, а затем перейти еще на один элемент. Пример:
$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 key for possible use in the next iteration
}
В конце этого скрипта, $ prev и $ next будет либо содержать ключ предыдущего/следующего элемента, либо быть ложным (если текущий элемент не найден или мы находимся в самом начале/конце массива и не предваряем/следующий).
array yp_next (строка $ domain, string $ map, string $ key) Возвращает следующую пару ключ-значение в именованной карте после указанного ключа.
Похоже, что вам нужен javascript. Он сможет выполнять коммутацию продуктов на стороне клиента, поэтому вы можете сохранить переменную из цикла for, а при нажатии кнопки вы можете вызвать функцию, чтобы переключить ее на следующую.
Вы не можете делать next() и prev() в ассоциативном массиве. Вам нужна другая структура массива, например:
$products = array();
$products[0] = 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[1] = 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[2] = 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[3] = 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[4] = 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)
);
Вы все еще можете перебирать эту структуру и получать имя текущего элемента из ключевого "имя".