将阵列复制/修剪为特定大小

时间:2012-10-01 10:33:58

标签: php multidimensional-array

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

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

$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', 
);

我如何实现这一目标?

谢谢!

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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));

应该可以正常工作