如何仅保留唯一值
if (enabled) {
ViewCompat.setBackgroundTintList(btn, getResources().getColorStateList(R.color.button_states)); // either use a single color, or a state_list color resource
} else {
ViewCompat.setBackgroundTintList(btn, ColorStateList.valueOf(Color.GRAY));
}
// make sure we're always clickable
btn.setEnabled(true);
btn.setClickable(true);
我想实现这样的结果
<?php
header('Content-Type: application/json');
function super_unique($array,$key){
$temp_array = [];
foreach ($array as &$v) {
if (!isset($temp_array[$v[$key]]))
$temp_array[$v[$key]] =& $v;
}
$array = array_values($temp_array);
return $array;
}
$arr = array();
$arr[0]['id'] = null;
$arr[0]['name'] = 'John';
$arr[1]['id'] = 12;
$arr[1]['name'] = 'John';
$arr[2]['id'] = null;
$arr[2]['name'] = null;
$arr[3]['id'] = 54;
$arr[3]['name'] = 'Ammie';
$arr[4]['id'] = 23;
$arr[4]['name'] = 'Martin';
$arr[5]['id'] = 54;
$arr[5]['name'] = null;
$arr[6]['id'] = 342;
$arr[6]['name'] = 'Anna';
$arr[7]['id'] = 64;
$arr[7]['name'] = 'Tom';
$arr[8]['id'] = 64;
$arr[8]['name'] = null;
$arr[9]['id'] = 364;
$arr[9]['name'] = null;
$arr[10]['id'] = null;
$arr[10]['name'] = 'Piter';
$arr = super_unique($arr,'id');
$arr = super_unique($arr,'name');
$arr = array_values($arr);
echo json_encode($arr);
?>
使用Peter不会向我显示结果,而John给出的ID为空
如果id相同,则必须按名称检查并仅保留一个且不为null,如果唯一值为null,则仅保留null
喜欢的ID:364 空名称
以及名称 我希望约翰ID是12
有什么建议吗?谢谢!
答案 0 :(得分:0)
您可以按以下方式重写唯一方法:
//This function will get you the missing field from the array:
function getField($arr, $key, $value, $newKey) {
foreach($arr as $e)
if (($e[$key] == $value) && $e[$newKey])
return $e[$newKey];
}
$res = array();
foreach($arr as $a) {
if (!$a["id"] && !$a["name"])
continue; // if both null ignore
if (!$a["id"]) // if id missing go get it
$a["id"] = getField($arr, "name", $a["name"], "id");
if (!$a["name"]) // fill the name if missing
$a["name"] = getField($arr, "id", $a["id"], "name");
$res[] = $a; // as to result array
}
$r = array_map("json_decode", array_unique(array_map("json_encode", $res))); // remove all duplicate elements
这将打印出来:
echo json_encode(array_values($r));
[{"id":12,"name":"John"},{"id":54,"name":"Ammie"},{"id":23,"name":"Martin"},{"id":342,"name":"Anna"},{"id":64,"name":"Tom"},{"id":364,"name":null},{"id":null,"name":"Piter"}]