查找下一个并在数组中预览元素

我是PHP的初学者。


我有这个数组:


$array = array(

    ['name' => 'project 1', 'url' => 'www.name1.com', 'photo' => '1.jpg'],

    ['name' => 'project 2', 'url' => 'www.name2.com', 'photo' => '2.jpg'],

    ['name' => 'project 3', 'url' => 'www.name3.com', 'photo' => '3.jpg'],

    ['name' => 'project 4', 'url' => 'www.name4.com', 'photo' => '4.jpg'],

    ['name' => 'project 5', 'url' => 'www.name5.com', 'photo' => '5.jpg'],

    ['name' => 'project 6', 'url' => 'www.name6.com', 'photo' => '6.jpg'],

)

我需要通过数组中的下一个和上一个元素(如果存在)获取函数:


$next = next($actualUrl);

$previous = previous($actualUrl);

我该怎么做?


DIEA
浏览 131回答 3
3回答

料青山看我应如是

这个简单的代码将帮助您:<?phpfunction next_elm ($array, $actualUrl) {&nbsp; &nbsp; $i = 0;&nbsp; &nbsp; while ( $i < count($array) && $array[$i]["url"] != $actualUrl ) $i++;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if ($i < (count($array) - 1)) {&nbsp; &nbsp; &nbsp; &nbsp;return $array[$i+1];&nbsp; &nbsp;} else if ($i == (count($array) - 1)) {&nbsp; &nbsp; &nbsp; &nbsp;return $array[0];&nbsp; // this is depend what you want to return if the url is the last element&nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp; &nbsp;return false; // there is no url match&nbsp; &nbsp;}&nbsp; &nbsp;&nbsp;}function prev_elm ($array, $actualUrl) {&nbsp; &nbsp; $i = 0;&nbsp; &nbsp; while ( $i < count($array) && $array[$i]["url"] != $actualUrl ) $i++;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;if ($i < (count($array)) && $i>0) {&nbsp; &nbsp; &nbsp; &nbsp;return $array[$i-1];&nbsp; &nbsp;} else if ($i == 0) {&nbsp; &nbsp; &nbsp; &nbsp;return $array[count($array) - 1];&nbsp; // this is depend what you want to return if the url is the first element&nbsp; &nbsp;} else {&nbsp; &nbsp; &nbsp; &nbsp;return false; // there is no url match&nbsp; &nbsp;}&nbsp; &nbsp;&nbsp;}

ibeautiful

我更喜欢通过 foreach 循环遍历任何数组。如果您想从中获取任何特定内容,只需将其复制到 TMP 变量中即可。例如:$tmp_var = null;foreach($array as $key => $value){&nbsp; &nbsp;$tmp_var = $value['name'];}

qq_遁去的一_1

首先查找实际 URL,然后使用此索引查找上一项和下一项。此外,您还应该添加检查当前项目是第一个还是最后一个元素,以避免空指针异常。$curr = 0;foreach($array as $value){&nbsp; &nbsp; if($value['url'] == 'www.name2.com'){&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }&nbsp; &nbsp; $curr += 1;}$previous = $array[$curr-1];$next = $array[$curr+1];
打开App,查看更多内容
随时随地看视频慕课网APP