dongzhao4036 2016-11-30 09:22
浏览 29
已采纳

编辑阵列放置

I am having a simple issue with ordering an array elements. Let's assume we have an array like this

[0]=>zero
[1]=>one
[2]=>two
[3]=>three

What i want is a way to move some elements to first position for example move one and two to first positions so i will have:

[1]=>one
[2]=>two
[0]=>zero
[3]=>three

and this should be done without knowing the current position of the element in the array which means it should be done by specifying the name of wanted element to move. I thought about array_splice() but it won't work since i should specify the key of the element in array.

  • 写回答

2条回答 默认 最新

  • dongmingxiang0312 2016-11-30 09:29
    关注

    You could build two arrays (one with the searched values and one without) and merge them. Keep in mind that if you want to keep numeric keys, you should use the + operator instead of array_merge :

    <?php
    
    $array = array('zero', 'one', 'two', 'three');
    $searched_values = array('one', 'two');
    $array_first = $array_second = array();
    
    foreach ($array as $key=>$value) {
        if (in_array($value, $searched_values))
            $array_first[$key] = $value;
        else
            $array_second[$key] = $value;
    }
    
    $array_end = $array_first + $array_second;
    
    echo '<pre>'; print_r($array_end); echo '</pre>';
    

    Returns :

    Array
    (
        [1] => one
        [2] => two
        [0] => zero
        [3] => three
    )
    

    EDIT : Keeping the $searched_values order

    In this case, you just need to loop over the serached values in order to build an array of found values and simultaneously delete the initial array's entry :

    <?php
        $array = array('zero', 'one', 'two', 'three'); 
        $searched_values = array('one', 'three', 'two');
        $array_found = array();
        foreach ($searched_values as $key=>$value) {
            $found_key = array_search($value, $array);
            if ($found_key !== false) {
                $array_found[$found_key] = $value;
                unset($array[$found_key]);
            }
        }
        $array_end = $array_found + $array;
        echo '<pre>'; print_r($array_end); echo '</pre>';
    ?>
    

    Returns :

    Array
    (
        [1] => one
        [3] => three
        [2] => two
        [0] => zero
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向