[英]Filter Array based on if contains php
My aim here is to remove the whole object from the array if "record_type" is null.如果“record_type”是 null,我的目标是从数组中删除整个 object。 I should then only be left with data that has a record_type set in the array.
然后,我应该只剩下在数组中设置了 record_type 的数据。
I've looked into the array filter not sure how I target the data within the array "record_type".我查看了数组过滤器,不确定如何定位数组“record_type”中的数据。 My only other thought is to import to a database and then SQL query what I want then delete data I've had which is much more overkill.
我唯一的另一个想法是导入数据库,然后 SQL 查询我想要的内容,然后删除我拥有的数据,这更加矫枉过正。
<pre>
array:36 [▼
0 => array:3 [▼
"type" => "comment"
"line_index" => 0
"text_b64" => "OyBjUGFuZWwgZmlyc3Q6ODguMC4xMiAodXBkYXRlX3RpbWUpOjE2MTg1NDYxNDIgQ3BhbmVsOjpab25lRmlsZTo6VkVSU0lPTjoxLjMgaG9zdG5hbWU6cjExOC5sb24yLm15c2VjdXJlY2xvdWRob3N0LmNvbSBs ▶"
]
1 => array:3 [▼
"line_index" => 1
"text_b64" => "OyBab25lIGZpbGUgZm9yIG9ha3RyZWVkZW50YWxtb3J0aW1lci5jby51aw=="
"type" => "comment"
]
2 => array:3 [▼
"text_b64" => "JFRUTCAxNDQwMA=="
"line_index" => 2
"type" => "control"
]
3 => array:6 [▼
"line_index" => 3
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"record_type" => "SOA"
"ttl" => 30
"type" => "record"
"data_b64" => array:7 [▶]
]
4 => array:6 [▼
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"line_index" => 10
"record_type" => "NS"
"ttl" => 30
"type" => "record"
"data_b64" => array:1 [▶]
]
5 => array:6 [▼
"ttl" => 30
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"line_index" => 11
"record_type" => "NS"
"data_b64" => array:1 [▶]
"type" => "record"
]
</pre>
Goal: only be left with data that has a 'record_type' set (not null
) in the array目标:只留下数组中设置了“record_type”的数据(不是
null
)
Solution: use array_filter()
on your source array ( $arr
) and filter for records with 'record_type' != "NS"
(assuming "NS" is what you refer to as null
, or not set).解决方案:在您的源数组 (
$arr
) 上使用array_filter()
) 并过滤具有'record_type' != "NS"
的记录(假设 "NS" 是您所说的null
或未设置)。
<?php
$result = array_filter(
$arr,
function (array $record) {
if (isset($record['record_type'])) {
return $record['record_type'] != "NS";
} return null;
}
);
If you want to filter for only those records that are of a certain type, eg type 'record', following should help:如果您只想过滤特定类型的记录,例如类型“记录”,以下应该会有所帮助:
<?php
$result = array_filter(
$arr,
function (array $record) {
if ($record['type'] == 'record') {
return true;
} return false;
}
);
If your Goal is to filter array to remove any inner-array that hasn't a record_type , So use array_filter
with a callback function fn
to check that record_type
exist with isset
function.如果您的目标是过滤数组以删除任何没有record_type的内部数组,那么使用带有回调
array_filter
fn
的 array_filter 来检查record_type
是否存在isset
function。
array_filter($arr, fn($el)=>isset($el["record_type"]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.