Php 如何";写下;使用数组的字符串作为文本?
因此,我的问题可能不是最好的,对此表示抱歉。Php 如何";写下;使用数组的字符串作为文本?,php,arrays,sorting,key,matching,Php,Arrays,Sorting,Key,Matching,因此,我的问题可能不是最好的,对此表示抱歉。 我有一个带字符串的数组,希望在另一个数组的帮助下编写一个文本,将其用作顺序/键。这是输入: $words =["I","am","cool"]; $order =["2","0","1","0","1","2"]; //var_export($words); // array ( // 0 => 'I', // 1 => 'am', // 2 => 'cool', // ) 我想使用$order作为某种键来
我有一个带字符串的数组,希望在另一个数组的帮助下编写一个文本,将其用作顺序/键。这是输入:
$words =["I","am","cool"];
$order =["2","0","1","0","1","2"];
//var_export($words);
// array (
// 0 => 'I',
// 1 => 'am',
// 2 => 'cool',
// )
我想使用$order作为某种键来重新排列$words,以便获得以下输出:
"Cool I am I am cool"
非常感谢您的帮助,谢谢:)从空数组开始。
然后循环遍历order数组,并将单词数组部分添加到新字符串中
$my_string= array();
foreach ( $order as $index ) {
$index = int($index);
$my_string[] = ( isset($words[ $index]) ) ? $words[ $index ] : '' );
}
$my_string = implode(' ', $my_string);
echo my_string;
使用
$order
的值作为$words
的键
$words =["I","am","cool"];
$order =["2","0","1","0","1","2"];
$output = '';
foreach($order as $key) {
$output .= $words[$key] . ' ';
}
echo ucfirst(trim($output));
演示:
empty($real_key)
用于检查它是否是第一次迭代。也可以是==0
迭代顺序,并将其值用作单词的键;将下面的代码转换为php应该很简单
foreach (string orderIndexString in order) {
int orderIndexInt = System.Convert.ToInt16(orderIndexString); // convert string to int
if(orderIndexInt < 0 || orderIndexInt >= words.Length)
continue;
print (words[orderIndexInt]); // either print or add it to another string
}
foreach(按顺序排列的字符串orderIndexString){
int-orderIndexInt=System.Convert.ToInt16(orderIndexString);//将字符串转换为int
if(orderIndexInt<0 | | orderIndexInt>=words.Length)
继续;
打印(words[orderindxint]);//打印或将其添加到另一个字符串中
}
我建议使用array\u map
和join
没有必要这样做
- 使用
foreach进行手动迭代的副作用
语句或三元(if
)表达式?:
- 变量重新分配
- 使用
- 检查数组长度
function map_indexes_to_words ($indexes, $words) {
$lookup = function ($i) use ($words) {
return $words[(int) $i];
};
return join(' ', array_map($lookup, $indexes));
}
$words = ["I","am","cool"];
$order = ["2","0","1","0","1","2"];
echo map_indexes_to_words($order, $words);
// 'cool I am I am cool'
一个问题。当我运行代码时,我得到一个错误,它表示$order中的每个数字都未定义(索引未定义:1)。我的$order是用$order=explode(“\n”,$string)创建的;每个数字都是字符串中的一段。为什么不起作用?无论如何,谢谢你的解决方案:)这不是最好的答案。如果不小心使用了不在
$words
@RST索引范围内的值,则此代码将出错(空的
可以很容易地添加。虽然不清楚预期的结果会是什么,但据我所知,配对是相关的。这就是我的观点,还有另一个需要执行的检查。将字符串放在一起最好使用数组,然后内爆。更干净。@RST这是一个观点。