如何从对象中删除包含字符串的数组


How do you remove arrays containing a string from an object?

对不起,我甚至不太确定如何表达我的问题。

我正在尝试用一个奇怪的设置从公共JSON API中删除个人注册者信息。示例:

"posts" : [
  {
  "id": 9658,
  "type": "event",
  "custom_fields" : {
    "registered_person_0_name" : [ "John" ],
    "registered_person_1_name" : [ "Doe" ]
  } 

如果有帮助的话,这就是var_dump:

["custom_fields"]=>
  object(stdClass)#6601 (45) {
    ["registered_person_0_name"]=>
      array(1) {
        [0]=> string(8) "Beverley"
      }

注册人数未知,具体取决于事件,每个字段都会增加,如图所示。我以为我会unset()所有"registered_person"的实例,但我被难住了。

如果给$posts,我觉得我可以做一些事情,比如:

foreach ( $posts as $post ) {
  unset( $post->custom_fields->all_the_registered_persons_fields_that_match)
}

但我想不通。我曾尝试将custom_fields对象类型转换为数组,然后使用in_array,然后使用unset,但这似乎不起作用。

我很感激任何指点。如果我能提供更多信息,请告诉我。

循环遍历属性变量,如果它们与模式匹配,则取消设置。

foreach ($posts as $post) {
    $custom_fields = $post->custom_fields;
    foreach (get_object_vars($custom_fields) AS $name => $val) {
        if (preg_match('/^registered_person_'d+_name$/', $name)) {
            unset($custom_fields->{$name});
        }
    }
}

另一种选择是使用json_decode()的可选参数,以便它返回关联数组而不是对象。然后您可以在数组上使用foreach

foreach ($posts as &$post) {
    $custom_fields = &$post['custom_fields'];
    foreach ($custom_fields AS $name => $val) {
        if (preg_match('/^registered_person_'d+_name$/', $name)) {
            unset($custom_fields[$name]);
        }
    }
}

请注意,在这种情况下,您必须使用引用变量,因为分配数组通常会产生副本。

假设您有一个包含要删除的字段的数组,则可以使用->{$propName}来实现这一点。->{$someVar}允许您动态访问对象的属性。

例如:

$field1 = "name";
echo($object->{$field}) // will echo the name property

在您的情况下:

$sensibleFields = ['creditCardNumber', 'socialSecurityNumber'];
foreach ($posts as $post) {
    foreach ($sensibleFields as $fieldName) {
        unset($post->{$fieldName});
    }
}

如果使用json_decode($the_api_data, true)获取结果数组样式而不是对象样式,则可以使用array_filter删除不需要的键。

foreach ($posts as &$post) {  // need to use a reference here for this to work
    $post['custom_fields'] = array_filter($post['custom_fields'], function($key){
        return 'registered_person_' != substr($key, 0, 18);
    }, ARRAY_FILTER_USE_KEY);
}