PHP:修改数组的元素序列

时间:2016-12-19 18:59:22

标签: php arrays sorting multidimensional-array

我从Excel文件中获得了一个php数组,例如:

$ arrayOne

Array
{
 [0] => Array
       {
        [0] => 0_age
        [1] => 1_academic id
        [2] => 2_name
        [3] => 3_sex
       }
 [1] => Array
       {
        [0] => 0_18
        [1] => 1_110291
        [2] => 2_Jason
        [3] => 3_Male
       }
  }

并且在proccess的中间,来自索引[0]的数组值包含来自 Excel Header 的数据,设置为duallistbox以进行消除和排序,然后设置为新数组$newArray 。那么,我得到了这个数组结果:

$ newArray

Array
{
 [0] => Array
       {
        [0] => 2_name
        [1] => 1_academic id
        [2] => 3_sex
       }
 }

我希望系统还可以从包含 Excel Data 的索引[1]中删除和排序数组的数据。 所以预期的结果是这样的:

$ expectedArray

Array
{
 [0] => Array
       {
        [0] => 2_Jason
        [1] => 1_110291
        [2] => 3_Male
       }
 }

任何人都知道想法或如何解决这个案子?我在每个可能对排序有用的数组值中添加了 id(例如:0 _)。 感谢

被修改

排序基于已在每个数组值上设置的 id ,因此来自[1]的数组索引$arrayOne上的每个元素都会重置为新的序列自适应来自$newArray id

1 个答案:

答案 0 :(得分:0)

单程

    <?php
$arr = array(
 array
       (
        "0_age",
        "1_academic id",
        "2_name",
        "3_sex",
       ),
 array
       (
        "0_18",
        "1_110291",
        "2_Jason",
        "3_Male",
       ),
    array
       (
        "0_28",
        "1_110291111",
        "2_Jason Second",
        "3_Female",
       )
  );

?>
<pre>
<?php 
$new_array = array();
$count = 0;
foreach($arr as $a){
    if($count==0){

    }else{
        $new_array[] = array(
            $arr[0][0] => $a[0],
            $arr[0][1] => $a[1],
            $arr[0][2] => $a[2],
            $arr[0][3] => $a[3],
        );
    }

    $count=$count+1;
}
print_r($new_array);
?>
</pre>

<强>输出

 Array
(
    [0] => Array
        (
            [0_age] => 0_18
            [1_academic id] => 1_110291
            [2_name] => 2_Jason
            [3_sex] => 3_Male
        )

    [1] => Array
        (
            [0_age] => 0_28
            [1_academic id] => 1_110291111
            [2_name] => 2_Jason Second
            [3_sex] => 3_Female
        )

)

与您的输出完全匹配的第二种方式

    $new_array = array();
$count = 0;
foreach($arr as $a){
    if($count==0){

    }else{
        $new_array[] = array(
            //$a[0],
            $a[2],
            $a[1],
            $a[3],
        );
    }

    $count=$count+1;
}
print_r($new_array);

<强>输出:

 Array
(
    [0] => Array
        (
            [0] => 0_18
            [1] => 1_110291
            [2] => 2_Jason
            [3] => 3_Male
        )

    [1] => Array
        (
            [0] => 0_28
            [1] => 1_110291111
            [2] => 2_Jason Second
            [3] => 3_Female
        )

)

您可以搜索,排序和删除任何字段。根据您的要求更新。