获取数组中的上一个和下一个值


Get previous and next values in array

>我有数组,例如:

<?php
$array = array(
  0 => array(
     'subject' => 'Stackoverflow',
     'body'    => '',
     'name'    => 'php'
   ),
  1 => array(
     'subject' => 'Test',
     'body'    => 'Wayne',
     'name'    => ''
   ),
  2 => array(
     'subject' => '',
     'body'    => 'this is ok',
     'name'    => ''
   ),
  3 => array(
     'subject' => 'cnn',
     'body'    => 'Google',
     'name'    => 'private'
   ),
  4 => array(
     'subject' => 'code',
     'body'    => '',
     'name'    => '7777'
   )
);
我想获取键

2 的主题、正文和名称,如果键不存在,那么这应该从上一个和下一个(单独的函数)值中获取。

例如,如果我想从 2 键中获取值:

function getCurrentOrPrevious(2); 

应返回:

   array(
     'subject' => 'Test', //from [1]
     'body'    => 'this is ok', //from [2] - current and exist
     'name'    => 'php' //from [0] - in from [2] and [1] not exist
   )
function getCurrentOrNext(2); 

应返回:

   array(
     'subject' => 'cnn', //from [3]
     'body'    => 'this is ok', //from [2] - current
     'name'    => 'php' //from [3] 
   )
最好的

方法是什么?PHP 中是否有用于此类操作的函数?

假设你填充数组类似于 $array[] = $value;[即您有从零开始的连续数字键]:

## $array is the array to take values from, $key is the target key
## $fields are required fields
function getCurrentOrPrevious($array, $key, $fields) {
    if ($key < 0) return null;
    $output = array();
    foreach ($fields as $field) {
       for ($i = $key; $i >= 0; $i--) {
         if (!empty($array[$i][$field])) {
            $output[$field] = $array[$i][$field];
            break;
         }
    }
    return $output;
}

按如下方式使用:

$my_values = getCurrentOrPrevious($array, 12, array('subject', 'body', 'name'));

我想你可以使用 php 的 empty() 函数来检查。你还应该考虑一下这个函数外壳能走多远?

  • 如果[3](下一个)在同一位置也有空值怎么办
  • 如果以前的索引<0怎么办?

更新

function getCurrOrNext($array, $index){
    $keys = array_keys($array[$index]);
    foreach($keys AS $key){
        if($array[$index][$key] == "") {
            $array[$index][$key] = (!empty($array[$index+1]) && !empty($array[$index+1][$key])?$array[$index+1][$key]:null);
        }
    }
    return $array;
}

我猜是这样的

function getCurrentOrPrev($array, $key) {
    while(key($array)!==$key) next($array); //move internal pointer to required position first
    $result = current($array);
    //loop is going to execute as long as at least one of elements is empty and we didn't get to beginning of array yet
    while((empty($result['subject'])
          || empty($result['body'])
          || empty($result['name'])) 
          && prev($array)!==false) {
        $c = current($array);
        //replace empty elements with values of current element
        $result['subject'] = empty($result['subject']) ? $c['subject'] : '';
        $result['body'] = empty($result['body']) ? $c['body'] : '';
        $result['name'] = empty($result['name']) ? $c['name'] : '';
    }
    return $result;
}

对于带有next的函数,只需将prev()方法替换为next(),或者为了尽量减少代码重复,您可以引入第三个参数并根据其值调用正确的方法。

此方法不关心参数中指定的键以外的键的值。您可能混合了文字索引和数字索引。