如何保持数组的特定元素始终在中间? PHP

时间:2016-12-12 00:19:27

标签: php arrays

我遵循生成语言数组的php:

<?php
/**
 * Language chooser for qtranslate-x plugin
 *
 * @package
 */

function get_language_list() {

    if ( function_exists( 'qtranxf_getSortedLanguages' ) ) {

        global $q_config;

        $list = array();
        foreach ( qtranxf_getSortedLanguages() as $key => $language ) {
            $list[] = array(
                'url' => qtranxf_convertURL( '', $language, false, true),
                'lan' => $q_config['language_name'][ $language ],
                'cur' => $language == $q_config['language'] ? 'current' : '',
            );
        }



        return $list;
    }

}

很棒,但是我需要以一种方式重写这个数组,即'cur' == 'current'的元素总是在中间,例如关键是1。

数组有3个元素。 dump看起来像这样:

array(3) {
  [0]=>
  array(3) {
    ["url"]=>
    string(24) ".dev/en/"
    ["lan"]=>
    string(7) "English"
    ["cur"]=>
    string(0) ""
  }
  [1]=>
  array(3) {
    ["url"]=>
    string(24) ".dev/ka/"
    ["lan"]=>
    string(21) "ქართული"
    ["cur"]=>
    string(0) ""
  }
  [2]=>
  array(3) {
    ["url"]=>
    string(24) ".dev/ru/"
    ["lan"]=>
    string(14) "Русский"
    ["cur"]=>
    string(7) "current"
  }
}

请注意,问题是此订单是随机发生的,只有当前的订单应始终位于中间。

2 个答案:

答案 0 :(得分:0)

我会说:

1)搜索当前并将其从数组中删除

2)然后将其重新插入数组的中间

$current = array_splice($list, 
    array_search('current', array_column($list, 'cur')), 1);
array_splice($list, round(count($list)/2), 0, $current);

答案 1 :(得分:0)

由@flynorc

建议
/**
 * Language chooser for qtranslate-x plugin
 *
 * @package marcopolo
 */

function get_language_list() {

    if ( function_exists( 'qtranxf_getSortedLanguages' ) ) {

        global $q_config;

        $list = array();
        foreach ( qtranxf_getSortedLanguages() as $key => $language ) {
            if ( $language == $q_config['language'] ) {
                $cur = true;
                $cur_key = $key;
            } else {
                $cur = false;
            }
            $list[ $key ] = array(
                'url' => qtranxf_convertURL( '', $language, false, true),
                'lan' => $q_config['language_name'][ $language ],
                'cur' => $cur,
            );
        }

        $middle = $list[1];
        $list[1] = $list[ $cur_key ];
        $list[ $cur_key ] = $middle;

        return $list;
    }

}