如何按特定顺序重新排序此数组?

时间:2014-05-14 22:40:36

标签: php

我有这个随机数字串需要将一些整数转换成字母。请注意,字符串中需要两个位置来制作一个字母。

01110413 Original string

此字符串最终应转换为:

A11D13   Converted string

到目前为止,这是我的代码

$id  = '01110413';

$chg = array(0 => array(0, 1), 3 => array(4, 5));
$ltr = array(00 => 'A', 01 => 'B', 03 => 'C', 04 => 'D');

$id = str_split($id);

foreach($chg as $ltrpos => $val){

    // $ltrpos; letter position placement in string AFTER conversion to letter

    $ltrkey = null;

    foreach($val as $idkey){
        $ltrkey .= $id[$idkey];
        unset($id[$idkey]);

        if(!empty($ltrkey)){
          $out[$ltrpos] = $ltr[(INT)$ltrkey];
        }
    }
}

运行此代码会给出:

Array
(
    [0] => B
    [3] => D
)

我需要在旧整数值所在的位置插入这些新值。 $chg数组键是值应在转换后的字符串中的位置。

如何订购我的最终$out数组,以便将未设置的整数替换为其所在位置的转换后的字母?

2 个答案:

答案 0 :(得分:0)

这应该这样做:

$id  = '01110413';

// your string codes always take up two positions, so you just need to provide the final position in the string
$chg = array(0,3);
// You could actually change 00 to just 0 (since they're integers).  Also, later in the script, the two character position is cast to an int, so it will match these values.
$ltr = array(00 => 'A', 01 => 'B', 03 => 'C', 04 => 'D');

$converted_id = doConvert($id, $ltr, $chg);

function doConvert($id, $conversion_codes, $final_position) {
    if( count($final_position) == 0 ) return $id;

    $next_pos = array_shift($final_position);

    // convert the two characters at the next position to a letter
    $id = substr($id, 0, $next_pos) . $conversion_codes[(int) substr($id, $next_pos, 2)] . substr($id, $next_pos+2); // (cast to an (int) so it will match the keys in our conversion array)

    return doConvert($id, $conversion_codes, $final_position);
}

此示例的输出为:

B11D13

你说第一个值应该是A,而是01 => B,这就是为什么第一个字母是B

答案 1 :(得分:0)

如果原始ID中的每两个字符都是代码,则可以使用更通用的字符,如下所示:

$id  = '01110413';

$conversion = array('00' => 'A', '01' => 'B', '03' => 'C', '04' => 'D');

$converted_id = "";
for($i=0; $i < strlen($id); $i+=2) {
    $char_code = substr($id, $i, 2);
    // we don't know this code, just append it
    if( empty($conversion[$char_code]) ) {
        $converted_id .= $char_code;
    }
    // convert and append
    else {
        $converted_id .= $conversion[$char_code];
    }
}