如何按值过滤多维数组?我想在这里删除带有重复符号的硬币:
$input = [
["name" => "Bitcoin", "symbol"=> "BTC"],
["name" => "Ethereum", "symbol"=> "ETH"],
["name" => "Bitcoin Cash", "symbol"=> "BCH"],
["name" => "Basic Attention Token", "symbol"=> "BAT"],
["name" => "BatCoin", "symbol"=> "BAT"]
]
输出为具有此类唯一硬币符号的数组。
$output = [
["name" => "Bitcoin", "symbol"=> "BTC"],
["name" => "Ethereum", "symbol"=> "ETH"],
["name" => "Bitcoin Cash", "symbol"=> "BCH"],
["name" => "Basic Attention Token", "symbol"=> "BAT"]
]
我试过
$symbols = array_map(function($coin){
return $coin['symbol'];
}, $input);
$output = array_filter($input, function($coin) use ($symbols) {
return in_array($coin['symbol'], $symbols);
});
return $output;
但我仍然列出了5个硬币。
答案 0 :(得分:1)
您可以获得如下所示的独特对象
// make it json string first
$jsondata = '[{"name": "Bitcoin","symbol": "BTC"},{"name": "Ethereum","symbol": "ETH"},{"name": "Bitcoin Cash","symbol": "BCH"},{"name": "Basic Attention Token","symbol": "BAT"},{"name": "BatCoin","symbol": "BAT"}]';
// decode string to json objects which will generate like yours
$objects = json_decode($jsondata);
echo'<pre>';
// print first objects
print_r($objects);
$symbolHolder=[];
foreach ($objects as $key => $object) {
// eliminate object from array which is identical symbol to others
if(in_array($object->symbol, $symbolHolder))
{
array_splice($objects, $key,1);
}
array_push($symbolHolder, $object->symbol);
}
// now printing unique array of object
print_r($objects);
答案 1 :(得分:0)
想出来
$unique_dict = [];
foreach($input as $obj) {
$symbol = $obj['symbol'];
$unique_dict[$symbol] = $obj;
}
$unique_array = array_values($unique_dict);
答案 2 :(得分:0)
您可以使用数组函数执行此任务。
array_column - 返回数组的单个列中的值,由列键标识。
array_unique - 获取一个输入数组并返回一个没有重复值的新数组。
array_intersect_key - 返回一个数组,其中包含array1的所有条目,其中包含所有参数中都存在的键。
示例:
<?php
$json = '[
{"name": "Bitcoin", "symbol": "BTC"},
{"name": "Ethereum", "symbol": "ETH"},
{"name": "Bitcoin Cash", "symbol": "BCH"},
{"name": "Basic Attention Token", "symbol": "BAT"},
{"name": "BatCoin", "symbol": "BAT"}
]';
$array = json_decode($json, true);
echo json_encode(
array_intersect_key(
$array,
array_unique(array_column($array, 'symbol'))
)
);