Php 如何按特定顺序重新排列此数组?
我有一组随机数,需要将一些整数转换成字母。请注意,它在字符串中有两个位置来组成一个字母Php 如何按特定顺序重新排列此数组?,php,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'
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
)
我需要将这些新值插入旧整数值所在的位置数组键是值在转换字符串中的位置。
如何对最终的$out
数组进行排序,以便用转换后的字母替换未设置的整数?这应该可以做到:
$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
如果原始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];
}
}
$id='01110413';
$conversion=array('00'=>'A','01'=>'B','03'=>'C','04'=>'D');
$converted_id=“”;
对于($i=0;$i
“$chg数组键是值应位于转换字符串中的位置”–不知道这意味着什么,分别是。它是如何应用于所给出的最小示例的。我举一个例子:A11D13转换字符串
。请参见位置0
和3
?“我需要将这些新值插入旧整数值所在的位置”-也不清楚-您以前是否已经替换了整数B
甚至不在你预先给出的最终结果中,而D
是否存在是因为04
已经被它取代了,不是吗?你不能这样做吗?“没人有线索”-相当大胆的陈述,考虑到你对实际实现的描述缺乏可理解性!不管怎样,你应该更新你原来的问题,而不是问一个新问题。谢谢Cully。我还在寻找kingkeros的解决方案。Cully,我试过这个,到目前为止,这似乎是我想要的。非常感谢。