我有以下代码:
<?php
//Page info
$PageTitle = "Johnson electrician";
$search_for =
array('Electrical Serviceh' => array('electrical', 'audio', 'electrician', 'security'), 'Plumbing Servicey' => array('heating', 'gas'));
foreach ($search_for as $name=>$term){
foreach ($term as $findme)
{
if (strpos($PageTitle,$findme) !== false)
{
echo $name;
}
}
}
?>
表示&#34; echo $ name;&#34;我希望它的$ name成为一个变量,我可以在以后的任何地方使用,但只是回显$ name只是在脚本之外使用时给我一个字段,而不是脚本的输出:
我尝试过以下操作,但不能使用多个输出:
在我的最后一步中使用单个值:http://codepad.viper-7.com/vowaKO,但是现在您可以输入多个值,当您直接回显它时,您将获得所有结果:http://codepad.viper-7.com/38sRBX。所以我尝试对你的新代码做同样的事情,所以它输出到一个我可以使用但却失败的变量:http://codepad.viper-7.com/9b4q3t
答案 0 :(得分:1)
您可以将$ name的值保存在另一个变量中以供将来参考。例如,在另一个数组中:
<?php
//Page info
$PageTitle = "Johnson electrician";
$nameArray = array();
$search_for = array('Electrical Serviceh' => array('electrical', 'audio', 'electrician', 'security'), 'Plumbing Servicey' => array('heating', 'gas'));
foreach ($search_for as $name=>$term){
foreach ($term as $findme)
{
if (strpos($PageTitle,$findme) !== false)
{
$nameArray[] = $name;
echo $name;
}
}
}
// to check the total array
print_r($nameArray);
// iterate over the array values
foreach ($nameArray as $name)
{
echo "<br/>".$name;
}
// to print selective values. note: index starts from 0
echo "<br/>".$nameArray[0];
echo "<br/>".$nameArray[1]; // and so on...
?>
根据评论部分的讨论更新了代码(仅限于回显$ name):
<?php
//Page info
$PageTitle = "Johnson electrician";
$nameArray = array();
$search_for = array('Electrical Serviceh' => array('electrical', 'audio', 'electrician', 'security'), 'Plumbing Servicey' => array('heating', 'gas'));
foreach ($search_for as $name=>$term){
foreach ($term as $findme)
{
if (strpos($PageTitle,$findme) !== false)
{
$nameArray[] = $name;
echo $name;
}
}
}
echo '<br><br>';
echo $name = implode($nameArray, ', ');
?>