PHP数组切片多维数组

时间:2015-04-11 18:38:39

标签: php arrays

我有一个多维数组,但需要将其缩小。 我相信这是一个简单的问题。我需要删除1个数组 jsonresult数组,第一个但在下一个数组中保留另一个。我试过了array_splice,但它只保留了一个。

Array
(
[searchword] => search word
[jsonresult] => Array
    (
        [0] => Array // THIS ONE, KEEP ITS CHILDREN MOVE UP
            (
                [0] => Array
                    (
                        [id] => 14889770
                    )
                   [1] => Array
                    (
                        [id] => 14389720
                    )
                   [2] => Array
                    (
                        [id] => 14869723
                    )
            )        

           [1] => Array // THIS ONE, KEEP ITS CHILDREN MOVE UP
            (
                [0] => Array
                    (
                        [id] => 14889722
                    )
                   [1] => Array
                    (
                        [id] => 14389711
                    )
                   [2] => Array
                    (
                        [id] => 14869329
                    )
            )           

   )
)

想得到:

Array
(
[searchword] => search word
[jsonresult] => Array
    (
       [0] => Array
        (
          [id] => 14889770
        )
                   [1] => Array
                    (
                        [id] => 14389720
                    )
                   [2] => Array
                    (
                        [id] => 14869723
                    )

                   [3] => Array
                    (
                        [id] => 14889722
                    )
                   [4] => Array
                    (
                        [id] => 14389711
                    )
                   [5] => Array
                    (
                        [id] => 14869329
                    )
    )           

)

1 个答案:

答案 0 :(得分:1)

试试这段代码。这可能不是正确的方法,但它可以满足您的需求。 (据我的问题理解)

//creating a sample array similar to one you given in question.
$arr_test['searchword'] = 'search word';
$arr_test['jsonresult'] = array(array(array('id'=>14889770),array('id'=>14889720)),array(array('id'=>14889780),array('id'=>14889790)));       
//creating new array
$arr_new = array();
//formatting array as you needed it
foreach($arr_test['jsonresult'] as $arr_jsonresult){
    foreach($arr_jsonresult as $jsonresult){        
        $arr_new['jsonresult'][] =  $jsonresult;        
     }
}
//overwriting the specific array key
$arr_test['jsonresult'] = $arr_new['jsonresult'];
//checking output
echo '<pre>';
print_r($arr_test);

此代码生成以下输出

Array
(
[searchword] => search word
[jsonresult] => Array
    (
        [0] => Array
            (
                [id] => 14889770
            )

        [1] => Array
            (
                [id] => 14889720
            )

        [2] => Array
            (
                [id] => 14889780
            )

        [3] => Array
            (
                [id] => 14889790
            )

    )

)