我正在构建一个过滤函数,该函数循环访问提供的数据以根据声明的数组键生成选择字段选项。
当键值为字符串时,我可以让我的函数输出预期的唯一结果,但是当我将键设置为数组时,我只得到前 1 个结果。
这是我的例子:
/* ----------------------
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 "=========> ";
var_dump($data);
print " <=========";
}
}
$data = '{"filter":[{"department":null,"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}}]}';
$response = json_decode($data, true);
// get unique values in array
function getUniqueValues($array, $args) {
$result = array();
foreach($array as $value) {
if(!empty($value[$args])) {
if(is_array($value[$args])) {
foreach ($value[$args] as $k => $v) {
$result[$k] = $v;
}
} else {
$result[] = $value[$args];
}
}
}
return array_unique($result);
}
dump(getUniqueValues($response['filter'], 'location'));
dump(getUniqueValues($response['filter'], 'department'));
任何键匹配"部门"的输出,输出预期结果
Array
(
[0] => Project Management
[2] => Customer Success
)
但是,当引用带有数组作为值的键时,我没有得到预期的结果。
Array
(
[country] => United Kingdom
[country_code] => GB
[region] => England
[city] => London
[zip_code] =>
)
我期待看到的是类似的东西。
Array
(
[0] => (
[country] => United Kingdom
[country_code] => GB
[region] => England
[city] => London
[zip_code] =>
),
[1] => (
[country] => United Kingdom
[country_code] => GB
[region] => England
[city] => Manchester
[zip_code] =>
)
)
我想我似乎错过了什么,或者我误解了array_unique($myArray)
的工作原理。无论如何,我该如何解决这个问题以提供正确的输出?
任何帮助将不胜感激。
谢谢:)
基于这个答案 https://stackoverflow.com/a/2561283/1376820,我修改了循环以将数组的每个值推送到新的数组$arrChild
。
if(is_array($value[$args])) {
array_push($arrChild, $value[$args] );
$result = array_intersect_key($arrChild, array_unique(array_map('serialize', $arrChild)));
}
完整示例如下: https://eval.in/990453