开发者

applying rule only once using in_array

Hello I was wondering how to do the following as I ha开发者_如何学Gove been going around without an answer. So I will try to simplify as much as I can.

I have set some values for an associative array

$vNArray ['Brandon']  = $item[3]; 
$vNArray['Smith']= $item[4]; 
$vNArray ['Johnson']= $item[5];
$vNArray ['Murphy']= $item[6];
$vNArray ['Lepsky']= $item[7];

foreach ($vNArray as $key => $value){

if(!empty($value)){
   $result  .= "\t\t\t\t<li><strong>$key</strong>"  .$value.   "</li>\n";
}

But now I want to target specific values within that array so here is another array:

$display_id=array('Brandon', 'Murphy');

foreach ($vNArray as $key => $value){
if(!empty($value)){
   //Looks into the display_id array and renders it differently
   if (in_array($key, $display_id)) {
   $data .= "\t\t<li id=\"".$vNArray['Brandon']."\">".$vNArray['Murphy']."</li>\n";

} else {
$result .= "\t\t\t\t<li><strong>$key</strong>$value</li>\n";
}

}

The result for the first condition is correct but repeated for both in_array values:

<li id="Brandon Value">Murphy Value</li>
<li id="Brandon Value">Murphy Value</li>

Below is correct:

<li><strong>Smith</strong> Value of Smith</li>
<li><strong>Smith</strong> Value of Johnson</li>
<li><strong>Lepsky</strong> Value of Lepsky</li>

How do I stop it from repeating depending on the number of arrays?


$data .= "\t\t<li id=\"".$vNArray['Brandon']."\">".$vNArray['Murphy']."</li>\n";

You've hardcoded the vNArray keys, so that regardless of which name got matched, you're always outputting the same values. You'd want

$data .= "\t\t<li id=\"{$key}\">{$value}</li>\n";

instead.

There's no need to do the string concatenation as you are. PHP can insert array elements into a string nicely, and it eliminates the need to escape quotes everywhere, which means for hideously ugly code to read through.


Look at your loop carefully.

You're using a foreach loop, which means you are going through the array each time.

Your if(in_array(...)) condition checks to see whether the key is in your $display_id array. That happens twice, for Brandon and Murphy.

When that condition happens twice, $data is appended twice meaning you will get the results displayed twice.

I'm not sure what this helps, but just look at your loops carefully. Can you clarify what you're exactly trying to achieve, or what your desired output is?

Good luck.

EDIT:

I reread your question and realized something -- do you just want your output to print once?

Look into the break syntax. After you append it in the if condition, add a break; and that will break out of the loop printing it once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜