在php中不重复的数组
我正在使用我的代码,允许用户输入一个单词,单词的每个字母都会给出一个含义 示例:用户输入文本“APPLE”。 输出: 每个字母的意思都是数组 我已经在这里有了我的代码,但是它的意思是重复的 例如:在php中不重复的数组,php,text,textcolor,Php,Text,Textcolor,我正在使用我的代码,允许用户输入一个单词,单词的每个字母都会给出一个含义 示例:用户输入文本“APPLE”。 输出: 每个字母的意思都是数组 我已经在这里有了我的代码,但是它的意思是重复的 例如: A - **Arrow** L - Love A - **Arrow** S - Soul 这是我的密码 <?php $chars = str_split("APPLE"); foreach($chars as $char){ if (substr($char, 0, 1) ===
A - **Arrow**
L - Love
A - **Arrow**
S - Soul
这是我的密码
<?php
$chars = str_split("APPLE");
foreach($chars as $char){
if (substr($char, 0, 1) === 'A')
{
$meaning = array("Angel","Ancient","Arrow");
echo $meaning[array_rand($meaning)];
}
}
?>
您可以保存以前使用的术语的“缓存”数组。例如:
<?php
$chars = str_split("APPLE");
$used_terms = array();
foreach($chars as $char){
if (substr($char, 0, 1) === 'A') {
$meaning = array("Angel","Ancient","Arrow");
do {
$term = $meaning[array_rand($meaning)];
} while (in_array($term, $used_terms));
$used_terms[] = $term;
echo $term;
}
}
?>
$chars = str_split("APPLE");
$words = array(
// its up to you what words you want to map
'A' => array("Angel","Ancient","Arrow"),
'E' => array('Elephat', 'Eardrum'),
'L' => array('Level', 'Laravel', 'Love'),
'S' => array('Sweet', 'Spicy', 'Savy'),
'P' => array('Powerful', 'Predictable', 'Pass', 'piss')
);
foreach($chars as $char){
$random_key = array_rand($words[$char]); // get random key
$key = $words[$char][$random_key]; // get the word
unset($words[$char][$random_key]); // unset it so that it will never be repeated
echo "$char - $key <br/>";
}
您可以在循环中临时取消设置它,这样就不会得到DUP。例如:
<?php
$chars = str_split("APPLE");
$used_terms = array();
foreach($chars as $char){
if (substr($char, 0, 1) === 'A') {
$meaning = array("Angel","Ancient","Arrow");
do {
$term = $meaning[array_rand($meaning)];
} while (in_array($term, $used_terms));
$used_terms[] = $term;
echo $term;
}
}
?>
$chars = str_split("APPLE");
$words = array(
// its up to you what words you want to map
'A' => array("Angel","Ancient","Arrow"),
'E' => array('Elephat', 'Eardrum'),
'L' => array('Level', 'Laravel', 'Love'),
'S' => array('Sweet', 'Spicy', 'Savy'),
'P' => array('Powerful', 'Predictable', 'Pass', 'piss')
);
foreach($chars as $char){
$random_key = array_rand($words[$char]); // get random key
$key = $words[$char][$random_key]; // get the word
unset($words[$char][$random_key]); // unset it so that it will never be repeated
echo "$char - $key <br/>";
}
$chars=str_split(“苹果”);
$words=数组(
//这取决于你想映射什么词
'A'=>数组(“天使”、“古代”、“箭头”),
'E'=>数组('Elephat','earrumn'),
'L'=>数组('Level','Laravel','Love'),
'S'=>数组('Sweet'、'spice'、'Savy'),
'P'=>数组('power'、'Predictable'、'Pass'、'piss')
);
foreach($chars作为$char){
$random_key=array_rand($words[$char]);//获取随机键
$key=$words[$char][$random_key];//获取单词
unset($words[$char][$random_key]);//将其取消设置,使其不再重复
回显“$char-$key
”;
}
My bad,这应该是一个do while循环。更新。不过,@Ghost的unset方法更有效:)