【问题标题】:PHP: Iterate through two arrays, find match, combinePHP:遍历两个数组,找到匹配,组合
【发布时间】:2016-07-22 17:40:03
【问题描述】:

我有一个包含当前票务信息的数组,如下所示:

[0] => Array
    (
        [id] => 1155643
        [text] => Physical Move and Assistance
        [location] => 25158 16th Ave NE, Lynnwood, WA, 98110, USA
        [company] => Blank Architecture, LLC.
        [site] => Main
        [contact] => First Last
        [start_date] => 2016-07-30 18:00:00
        [end_date] => 2016-07-30 22:00:00
        [technician] => First Last
        [hours] => 4
        [status] => Firm
        [ownerFlag] => 1
        [lat] => 47.54601 //Incorrect latitude
        [lng] => -122.22651 //Incorrect longitude
    )

[1] => Array //There are 70+ more...

我还有另一个数组,从中提取公司位置坐标:

[0] => Array
    (
        [company] => Rhodes and Associates
        [lat] => 47.32026
        [lng] => -122.30402
    )

[1] => Array //There are 130+ more...

从我们的系统中提取票证数据 (cURL) 后,我使用两个循环遍历两个数据集,但似乎无法获得正确的坐标以填充到更大的数据数组中。更具体地说,公司信息数组中唯一被拉取和填充的坐标对是迭代中的最后一对,[132]。

这是一个代码sn-p:

if ($ticket_number = $onsites) {
$current_onsites = array();
$i = 0;

$coordinates = json_decode(file_get_contents('geo.json'), true);
$crd = array();

for ($i = 0; $i <= count($ticket_number); $i++) {
    @$current_onsites[$i]['id'] = $ticket_number[$i];
    @$current_onsites[$i]['text'] = $summary[$i];
    @$current_onsites[$i]['location'] = $location[$i];
    @$current_onsites[$i]['company'] = $company[$i];
    @$current_onsites[$i]['site'] = $site[$i];
    @$current_onsites[$i]['location'] = $full_address[$i];
    @$current_onsites[$i]['contact'] = $contact[$i];
    @$current_onsites[$i]['start_date'] = date('Y-m-d H:i:s', strtotime($startDate[$i]));
    @$current_onsites[$i]['end_date'] = date('Y-m-d H:i:s', strtotime($endDate[$i]));
    @$current_onsites[$i]['technician'] = $technician[$i];
    @$current_onsites[$i]['hours'] = $hours[$i];
    @$current_onsites[$i]['status'] = $status[$i];
    @$current_onsites[$i]['ownerFlag'] = $ownerFlag[$i];

    foreach ($coordinates as $latlng){
        if ($latlng['input_id'] = @$current_onsites[$i]['company']) {
            @$current_onsites[$i]['lat'] = $latlng['metadata']['latitude'];
            @$current_onsites[$i]['lng'] = $latlng['metadata']['longitude'];
        } else {}
    }
}

print "<pre>";
print_r ($current_onsites);
print "</pre>";

//$fp = fopen('results.json', 'w');
//fwrite($fp, json_encode($current_onsites));
//fclose($fp);

我知道代码很脏,我只是想让它现在工作。任何想法都非常感谢。谢谢。

【问题讨论】:

    标签: php arrays json for-loop foreach


    【解决方案1】:
    if ($latlng['input_id'] = @$current_onsites[$i]['company']) {
    

    你只有一个 = —— 那是分配,而不是比较。

    但无论如何你都不应该那样做。两个循环将您的 O(n) 算法变成 O(n^2)。按公司名称重新索引第二个数组,以便您可以执行快速查找。

    【讨论】:

      猜你喜欢
      • 2019-04-08
      • 1970-01-01
      • 2018-02-13
      • 2017-12-16
      • 2020-07-04
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2014-09-23
      相关资源
      最近更新 更多