使用foreach和unset()在php数组中仅保留一组特定的数据

使用foreach和unset()在php数组中仅保留一组特定的数据,php,arrays,Php,Arrays,我有一个数组,其中包含从数据库收集的类别号。数组不是静态的,长度和内容可能会发生变化 根据if/else语句的结果,我需要删除数组中除了一个特定类别及其子类别之外的所有内容 我认为这是我需要的,但如果我使用它,我根本就得不到任何内容 foreach($this->data[$parent_id] as $key => $value) { if(!in_array($key, 131)) { unset($this->data[$parent_id][$key]); }

我有一个数组,其中包含从数据库收集的类别号。数组不是静态的,长度和内容可能会发生变化

根据if/else语句的结果,我需要删除数组中除了一个特定类别及其子类别之外的所有内容

我认为这是我需要的,但如果我使用它,我根本就得不到任何内容

foreach($this->data[$parent_id] as $key => $value) {
if(!in_array($key, 131)) {
    unset($this->data[$parent_id][$key]);
}
}

我以为我正在做的是获取所有数组数据,如果数组键不是131,请将其删除。

现在,代码是这样读取的:

/** For each, Array as $key => $value **/
foreach($this->data[$parent_id] as $key => $value) {
/** if needle $key is not found in Array 131, 
       which in this case is never **/
    if(!in_array($key, 131)) {
        /** destroy array[key], or in this case, all the elements**/
        unset($this->data[$parent_id][$key]);
    }
}
因此,上面应该会返回一个空数组。请参阅,以按适当的顺序传递适当的参数

如果您想要比较的只是当前迭代$this->data[$parent_id]与(例如)131的键,那么这就是您所需要的:

/** For each, Array as $key => $value **/
foreach($this->data[$parent_id] as $key => $value) {
/** if the current $key of the array element is not equal to number 131 **/
    if($key != 131) {
        /** destroy the array element**/
        unset($this->data[$parent_id][$key]);
    }
}
PS:更新我的答案,以反映在这种特定情况下,上述循环逻辑等效于以下内容:

/** 
 * If key 131 exists in data[$parent_id]
 *   assign an array with only thisArray[131] as an element, 
 *   where thisArray is data[parent_id]
 **/
if(array_key_exists(131, $this->data[$parent_id]))
    $this->data[$parent_id] = [$this->data[$parent_id][131]];

现在,您的代码是这样读取的:

/** For each, Array as $key => $value **/
foreach($this->data[$parent_id] as $key => $value) {
/** if needle $key is not found in Array 131, 
       which in this case is never **/
    if(!in_array($key, 131)) {
        /** destroy array[key], or in this case, all the elements**/
        unset($this->data[$parent_id][$key]);
    }
}
因此,上面应该会返回一个空数组。请参阅,以按适当的顺序传递适当的参数

如果您想要比较的只是当前迭代$this->data[$parent_id]与(例如)131的键,那么这就是您所需要的:

/** For each, Array as $key => $value **/
foreach($this->data[$parent_id] as $key => $value) {
/** if the current $key of the array element is not equal to number 131 **/
    if($key != 131) {
        /** destroy the array element**/
        unset($this->data[$parent_id][$key]);
    }
}
PS:更新我的答案,以反映在这种特定情况下,上述循环逻辑等效于以下内容:

/** 
 * If key 131 exists in data[$parent_id]
 *   assign an array with only thisArray[131] as an element, 
 *   where thisArray is data[parent_id]
 **/
if(array_key_exists(131, $this->data[$parent_id]))
    $this->data[$parent_id] = [$this->data[$parent_id][131]];

您应该在db查询中执行此操作吗?@rtfm同一个db查询也将数据传递到下拉菜单中。直接编辑查询将限制下拉列表可用的内容。我认为在将数组数据传递给第二个数据库之前修改数组数据更简单function@StevePrice,可能您试图实现一些不同的功能,但从代码来看,似乎不需要循环。由于数组索引是唯一的,您只需执行以下操作:
$this->data[$parent\u id]=[$this->data[$parent\u id][131]$this->data[$parent\u id]=[$this->data[$parent\u id][131]