php - 返回与数组

时间:2018-05-08 16:12:51

标签: php arrays multidimensional-array

我正在构建一个从托管的json文件中读取可用位置的职业页面。我很难通过超过数值来正确过滤数据。

此示例在与$data数组中设置的键/值进行比较时,尝试仅输出$filter数组中的匹配值:

<?php
    /* ----------------------
    Dump the output
    ---------------------- */
    function dump($data) {
        if(is_array($data)) { //If the given variable is an array, print using the print_r function.
            print "<pre>\n";
            print_r($data);
            print "</pre>";
        } elseif (is_object($data)) {
            print "<pre>\n";
            var_dump($data);
            print "</pre>";
        } else {
            print "=========&gt; ";
            var_dump($data);
            print " &lt;=========";
        }
    }

    /* ----------------------
    Sanitize a string to url friendly
    ---------------------- */
    function cleanString($str) {
        $removetags = array("'", '"', ',', '.', '?', '& ', '&amp; ', '/', '#', '@','(',')');
        $removespace[] = ' ';
        $notags = str_replace($removetags,"",$str);
        $nospaces = strtolower(str_replace($removespace,"-",$notags));
        return preg_replace('~-{2,}~', '-', $nospaces);
    }
    function sanitizeString($val) {
        if(is_array($val)) {
            $array = array() ;
            foreach ($val as $key => $value) {
                $array[$key] = cleanString($value);
            }
            return $array;
        } else {
            $result = cleanString($val);
        }
        return $result;
    }

    /* ----------------------
    Filter the array data, should match all values;=
    ---------------------- */
    function filterData($array, $filter) {
        $result = array();
        foreach ($filter as $gk => $gv) {
            foreach ($array as $key => $value) {
                if (array_key_exists($gk, $value) && !empty($value[$gk])) {
                    if(is_array($value[$gk])) {
                        $child = array_search($gv, sanitizeString($value[$gk]));
                        if(!empty($value[$gk][$child])) {
                            $theValue = sanitizeString($value[$gk][$child]);
                            if ($theValue ===  $gv ) {
                                array_push($result,$value);
                            }
                        }
                    } else {
                        $theValue = sanitizeString($value[$gk]);
                        if ($theValue ===  $gv ) {
                            array_push($result,$value);
                        }
                    }
                }
            }
        }
        return (!empty($result)) ? $result : $array;
    };

    // sample data
    $data = '{"jobs":[{"department":"sales","location":{"country":"United States","country_code":"US","region":"New York","region_code":"NY","city":"New York","zip_code":null,"telecommuting":false}},{"department":null,"location":{"country":"United Kingdom","country_code":"GB","region":"England","region_code":"England","city":"Leeds","zip_code":null,"telecommuting":false}},{"department":"Project Management","location":{"country":"United Kingdom","country_code":"GB","region":"England","region_code":"England","city":"Manchester","zip_code":null,"telecommuting":false}},{"department":"Project Management","location":{"country":"United Kingdom","country_code":"GB","region":"England","region_code":"England","city":"London","zip_code":null,"telecommuting":false}},{"department":"Customer Success","location":{"country":"United Kingdom","country_code":"GB","region":"England","region_code":"England","city":"London","zip_code":null,"telecommuting":false}},{"department":null,"location":{"country":"United Kingdom","country_code":"GB","region":"England","region_code":"England","city":"London","zip_code":null,"telecommuting":false}}]}';

    $decode = json_decode($data, true);


    // sample filter - values should be lowercase, and sanitised;
    $filter = array (
        'department' => 'project-management',
        'location' => 'london'
    );

    $filterdata = filterData($decode['jobs'], $filter);

    $i = 1;
    foreach ($filterdata as $res) {
        echo $i . '<br />';
        echo $res['department'] . '<br />';
        echo $res['location']['city'] . '<hr />';
        $i++;
    }
?>

我发现的是filterData函数将返回与$filter数组中任何设置键/值匹配的结果。如果部门和地点都匹配,我可以获得重复的条目。

如何调整此值以便我只得到所有$filter个键/值匹配的数组输出?

谢谢 - 我已经花了一天时间而且没有进一步,所以对于正确方向的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

注意:我可能不太了解你的问题但是,看到没有答案,我决定尝试。 如果我猜错了,请告诉我,我会相应地修改我的答案。

我会忽略你的cleanString&amp; sanitizeString现在正常运作。我相信您可以在解决作业过滤部分后轻松实现这些功能。

要过滤任何数据数组,array_filter()是您最好的朋友。

  

array_filter()迭代数组中的每个值,将它们传递给回调函数。如果回调函数返回true,则将数组中的当前值返回到结果数组中。数组键被保留。

array_filter()内部回调中,循环使用过滤规则,并检查$job是否具有匹配的属性。
如果所有规则都匹配,我们将返回true,否则为false(这将从阵列中过滤掉该作业)

$data = '{"jobs":[{"department":"sales","location":{"country":"United States","country_code":"US","region":"New York","region_code":"NY","city":"New York","zip_code":null,"telecommuting":false}},{"department":null,"location":{"country":"United Kingdom","country_code":"GB","region":"England","region_code":"England","city":"Leeds","zip_code":null,"telecommuting":false}},{"department":"Project Management","location":{"country":"United Kingdom","country_code":"GB","region":"England","region_code":"England","city":"Manchester","zip_code":null,"telecommuting":false}},{"department":"Project Management","location":{"country":"United Kingdom","country_code":"GB","region":"England","region_code":"England","city":"London","zip_code":null,"telecommuting":false}},{"department":"Customer Success","location":{"country":"United Kingdom","country_code":"GB","region":"England","region_code":"England","city":"London","zip_code":null,"telecommuting":false}},{"department":null,"location":{"country":"United Kingdom","country_code":"GB","region":"England","region_code":"England","city":"London","zip_code":null,"telecommuting":false}}]}';

    $decode = json_decode($data, true);

    $filters = array(
        'department' => 'Project Management',
        'location' => 'London'
    );

    /**
     * We will use array_filter()
     * to filter out jobs that doesn't meet our rules
     */
    $filterData = array_filter($decode['jobs'], function($job) use($filters) {
        $matched = [];

        foreach ($filters as $col => $val) {
            if (isset($job[$col]) === false) {
                $matched[0] = '';
                continue;
            }

            /**
             * I am assigning filter condition to $matched key
             * PHP as a dynamic language, will convert boolean to integer
             * 
             * If you don't like this approach, you can try assigning to value
             */
            if (is_array($job[$col])) {
                $matched[in_array($val, $job[$col])] = '';
            } else {
                $matched[($job[$col] === $val)] = '';
            }
        }

        /**
         * If any of our rules returned false
         * We will return false too
         * and array_filter will filter out this job
         */
        return isset($matched[0]) === false;
    });

    print_r($filterData);