Php 数组_search()不';最后一个键不匹配
我正在尝试创建一个函数,动态地获取特定页面的所有子页面。然后它将检查当前页面是什么,并抓取下三个页面作为预览显示 最后一页ID是6120。 您可以硬编码$pagesArray()和$lastKey以及$matches以查看结果Php 数组_search()不';最后一个键不匹配,php,arrays,search,Php,Arrays,Search,我正在尝试创建一个函数,动态地获取特定页面的所有子页面。然后它将检查当前页面是什么,并抓取下三个页面作为预览显示 最后一页ID是6120。 您可以硬编码$pagesArray()和$lastKey以及$matches以查看结果 $pagesArray( [0] => 6135 [1] => 6139 [2] => 6176 [3] => 6178 [4] => 6163 [5] => 6152 [6] => 6167 [7] => 6183 [8]
$pagesArray(
[0] => 6135
[1] => 6139
[2] => 6176
[3] => 6178
[4] => 6163
[5] => 6152
[6] => 6167
[7] => 6183
[8] => 6201
[9] => 6190
[10] => 6172
[11] => 6197
[12] => 6205
[13] => 6154
[14] => 6120
);
$lastKey = 14;
$matches = 14;
当我转到最后一页时,页面ID是6120,它是数组的第14个ID。
它应该返回前3个页面ID,但不匹配。请帮忙。这是代码。
作为参考,$matches==$lastKey应该是设置$nextPagesArray()的条件的一部分。他们都是14岁,但不匹配
function getNext3PortfolioPages(){
global $post;
$currentPage = $post->ID;
$last = '';
$lastKey = '';
$pagesArray = array();
$nextPagesArray = array();
$args = array(
'child_of' => '6115',
'offset' => $post->ID
);
// get all the page id's that are children of page 6115
$result = get_pages($args);
// add the page id's to the $pagesArray
foreach ( $result as $page ){
array_push($pagesArray, $page->ID);
}
//find the last page id in the array
$last = end($pagesArray);
// find the index of the last array value
$lastKey = key($pagesArray);
// find the index of the current page displayed
$matches = array_search($currentPage, $pagesArray);
// check to see if the current page index is the same as the end of the array
// and set up the $nextPagesArray with the next 3
if ( (int)$matches == (int)$lastkey ) {
//print_r('1');
//print_r($pagesArray);
array_push($nextPagesArray, $pagesArray[0]);
array_push($nextPagesArray, $pagesArray[1]);
array_push($nextPagesArray, $pagesArray[2]);
} elseif ( $matches == $lastkey - 1 ) {
//print_r('2');
array_push($nextPagesArray, $pagesArray[$lastKey]);
array_push($nextPagesArray, $pagesArray[0]);
array_push($nextPagesArray, $pagesArray[1]);
} elseif ( $matches == $lastkey - 2 ) {
//print_r('3');
array_push($nextPagesArray, $pagesArray[$lastKey - 1]);
array_push($nextPagesArray, $pagesArray[$lastKey]);
array_push($nextPagesArray, $pagesArray[0]);
} else {
//print_r('4');
array_push($nextPagesArray, $pagesArray[$matches + 1]);
array_push($nextPagesArray, $pagesArray[$matches + 2]);
array_push($nextPagesArray, $pagesArray[$matches + 3]);
}
return $nextPagesArray;
}
如果您想让数组“环绕”,可以这样使用前三个元素扩展数组:
输入:
$pages=[6135,6139,6176,6178,6163,6152,6167,6183,6201,6190,6172,6197,6205,6154,6120];
方法():
输出:
array (
0 => 6135,
1 => 6139,
2 => 6176,
)
这将节省您进行一系列条件检查的时间,并且无论搜索中使用的页码是多少(当然,只要该页码存在于数组中),它都可以工作。@JohnDavid很乐意提供帮助。如果你想让我澄清什么,就让我知道。我不会说谎,我充其量只是中间人,但我甚至没有想到这一点,这很有道理。没有条件从头到尾滚动。@JohnDavid在过去的3个月里,我才真正活跃起来,但我学到的东西太多了。这个地方是学习聪明技术和分享最佳实践的最佳场所。提前付款。快乐编码。
array (
0 => 6135,
1 => 6139,
2 => 6176,
)