dongnei3634 2012-09-21 06:13
浏览 41
已采纳

PHP - 使用foreach和数组

I'm struggling to get the correct syntax to to parse out the values from an array to use with the foreach loop. I have an array:

$contacts_array

which contains one or more names which I need to search on. The array looks like this:

Array
(
    [0] => PR1010

    [1] => PR1086
)   

If I was to manually generate the required PHP code with a known number of names it would look like this where there are 2 names to search on:

// Create first find request
$findreq1 =$fm->newFindRequest('Contacts');

// Create second find request
$findreq2 =$fm->newFindRequest('Contacts');


// Specify search criterion for first find request 
$findreq1->addFindCriterion('Name', $searchTerm);

// Specify search criterion for second find request 
$findreq2->addFindCriterion('Suburb', $searchTerm);;

// Add find requests to compound find command 
$request->add(1,$findreq1); 
$request->add(2,$findreq2); 

I need to generate the equivalent code for every name in the array. I know I need to use something like:

foreach($contacts_array as $contact_array => $value) 
{
} 

as well as:

$num = 1
$num++; } /* foreach record */

I'm just not sure how to bring this all together so that it increments the $findreq1 variables as I go. All my attempts so far generate errors. If anyone can show me how to combine this together that would be greatly appreciated as I'm learning PHP as I go.

Thanks

  • 写回答

2条回答 默认 最新

  • doumaque6551 2012-09-21 06:26
    关注
    <?php 
        for($i = 0; $i < count($contacts_array); $i++) { 
            ${'findreq' . ($i+1)} = $fm->newFindRequest('Contacts');
            ${'findreq' . ($i+1)}->addFindCriterion('Name', $contacts_array[$i]);
            $request->add($i+1, ${'findreq' . ($i+1)});
        }
    ?> 
    

    Read more about Dynamic variable names in PHP

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算