-1

编辑明确我需要它用于多维数组(在任何深度级别)

我需要减少数组的大小以仅获取其中的一部分,但这需要递归完成。例如,采取以下情况:

$a = array(
  'a',
  'b' => array(
    'x' => array(
      'aleph',
      'bet'
      ),
    'y'), 
  'c', 
  'd', 
  'e'
);

我需要的是,仅复制 4 个元素后,我将得到以下结果数组:

$a = array(
  'a',
  'b' => array('x' => array(
      'aleph'
    ),
  ), 
);

并不是...

$a = array(
  'a',
  'b' => array('x' => array(
      'aleph',
      'bet'
      ),
    'y'), 
  'c', 
  'd', 
);

我如何实现这一目标?

谢谢!

4

2 回答 2

1

function arrayTrim($array, $size,  $finalArray = null){
    global $count;
    foreach ($array AS $key => $val){
        if($size == $count)
            return $finalArray;
        $count++;
        if(is_array($val)){
            $finalArray[$key] = array();
            $finalArray[$key] = arrayTrim ($val, $size,  $finalArray[$key]);
        }
        else
            $finalArray[$key] = $val;
    }
    return $finalArray;
}
$a = array( "a"=> array('xa', 'ya'), "b" => array('x', 'y'),  "c", "d", "e" );

print_r(arrayTrim($a, 4));

应该可以正常工作

于 2012-10-01T11:16:17.000 回答
1

你可以试试**Note : dual-dimensional

    $a = array("a","b" => array('x','y'),"c","d","e");
$new = __cut($a);


function __cut($array, $max = 4) {
    $total = 0;
    $new = array();
    foreach ( $array as $key => $value ) {
        if (is_array($value)) {
            $total ++;
            $diff = $max - $total;
            $slice = array_slice($value, 0, $diff);
            $total += count($slice);
            $new[$key] = $slice;
        } else {
            $total ++;
            $new[$key] = $value;
        }
        if ($total >= $max)
            break;
    }
    return $new;
}

var_dump($new);

输出

array
  0 => string 'a' (length=1)
  'b' => 
    array
      0 => string 'x' (length=1)
      1 => string 'y' (length=1)
于 2012-10-01T10:43:17.300 回答