PHP数组循环键匹配

时间:2016-08-08 07:04:08

标签: php arrays

我只有这个图像数组($ images),我想通过给定的密钥遍历这些图像。

$images = array(0=>'image1', 1=>'image2', 2=>'image3');

让我们假设有这个分页,当我去每个页面时,它应该将图像键与页码匹配并返回图像。如果给定的图像键不存在,则应返回第一个图像。我在会话中有页码,这是我迄今为止所做的。

/*Default $key = 1;*/
$key = $_SESSION['page'];
$count = count($images);

$key = $SESSION['key'] = (array_key_exists($key-1, $images)) ? $key : ($_SESSION['key'] > $count? 1 : $_SESSION['key']+1);

$this_image = $images[$key-1];

当我浏览页面时,这将循环显示图像,但我希望它能够如下所示工作。

第1页>键0,第2页>键1,第3页>键2,第4页>键0,第5页>键1,第6页>关键2

例如,如果我转到第5页,它应该返回图像数组中的图像2。

我希望这是有道理的,并感谢你的帮助。

感谢。

4 个答案:

答案 0 :(得分:3)

$total = count($images);
$remainder = $page%$total;
echo $key = ($remainder == 1) ? 0 : (($remainder == 2)  ? 1 : 2);

答案 1 :(得分:1)

试试这个:

($key > $count) ?  $key = $key%$count : $key = $key-1;

答案 2 :(得分:0)

您的代码存在一些问题。一个人在$key存在时返回$key - 1,而$key - 1应该是$key = (isset($images[$key - 1])) ? $key - 1 : ($key > $count ? $key - $count - 1 : 0);

$http.post ('http: //localhost/proyectos/3.0copy/app/partials/createJson.php data', data) .then (function () {
console.log ($scope.variables);
});

答案 3 :(得分:-1)

这适用于任何情况。

.controller('taskCtrl', function ($scope, $http, $ionicPopup) {

$scope.tasksList = function () {
  $scope.listdata = [];
  for (var i = 0; i < 100; i++) {
    $scope.listdata.push(i)
  }
  var myPopup = $ionicPopup.show({
    template: ' <style>.popup { width:500px; height:50%; }</style> <ion-list>                           ' +
    '  <ion-item ng-repeat="item in listdata"> ' +
    '    {{item.id}}                              ' +
    '  </ion-item>                             ' +
    '</ion-list>                               ',
    title: 'Current Tasks',
    scope: $scope,
    buttons: [
      {
        text: '<b>Close</b>',
        type: 'button-positive',
        onTap: function (e) {
          myPopup.close();
        }
      },
    ]
  });
  myPopup.then(function (res) {
    console.log('Tapped!', res);
  });
};
})

特别感谢@ M.I和@ user1234,并感谢其他人的建议:)

相关问题