php数组:在表中搜索匹配的值并用数组键替换
Please i want to loop through my table and compare values with an array in a php included file. If there is a match, return the array key of the matched item and replace it with the value of the table. I need help in returning the array keys from the include file and comparing it with the table values.
$myarray = array(
"12aaa"=>"hammer",
"22bbb"=>"pinchbar",
"33ccr"=>"wood" );
in my loop in a seperate file
include 'myarray.inc.php';
while($row = $db->fetchAssoc()){
foreach($row as $key => $val)
if $val has a match in myarray.inc.php
{
$val = str_replace($val,my_array_key);
}
}
So in essence, if my db table has hammer and wood, $val will produce 12aaa and 3ccr in the loop. Any help? Thanks a lot
我想循环遍历我的表并将值与php包含的文件中的数组进行比较。 如果匹配,则返回匹配项的数组键,并将其替换为表的值。 我需要帮助从包含文件返回数组键并将其与表值进行比较。 p>
$ myarray = array(
“12aaa”=>“hammer” ,
“22bbb”=>“pinchbar”,
“33ccr”=>“wood”);
code> pre>
在我的循环中的单独文件中 p>
include'myarray.inc.php';
while($ row = $ db-> fetchAssoc()){
foreach($ row as $ key = > $ val)
如果$ val在myarray.inc.php
中有匹配
{
$ val = str_replace($ val,my_array_key);
}
}
code > pre>
所以从本质上讲,如果我的db表有锤子和木头,$ val将在循环中产生12aaa和3ccr。 有帮助吗? 非常感谢 p>
div>
You are looking for array_search
which will return the key associated with a given value, if it exists.
$result = array_search( $val, $myarray );
if ($result !== false) {
$val = $result;
}
your array should look like
$myarray = array(
"hammer"=>"11aaa",
"pinchbar"=>"22bbb",
"wood"=>"33ccr" );
and code
if (isset($myarray[$key])){
//do stuff
}
I think you need the function in_array($val, $myarray);
If you don't want or can't change $myarray
structure like @genesis proposed, you can make use of array_flip
include 'myarray.inc.php';
$myarray = array_flip($myarray);
while($row = $db->fetchAssoc()) {
foreach($row as $key => $val) {
if (isset($myarray[$val])) {
// Maybe you should use other variable instead of $val to avoid confusion
$val = $myarray[$val];
// Rest of your code
}
}
}