如何重新索引过滤数组

时间:2018-02-21 02:08:56

标签: php arrays

这实际上是原始数组

[radios1] => Array
        (
            [0] => on
        )

    [from] => Array
        (
            [0] => 
            [1] => Bangalore
            [2] => 
            [3] => 
        )

我想删除此数组的空键,因此我使用此代码执行此操作

`$array = array_map('array_filter', $_POST);
$array = array_filter($array);`

此输出如下

[radios1] => Array
        (
            [0] => on
        )

    [from] => Array
        (
            [1] => Bangalore
        )

这里我已经能够删除具有空值的键,但是应该重新索引过滤后的键。我用过两个

array_merge array_values `

但没有用iam得到相同的输出我想要输出

[radios1] => Array
        (
            [0] => on
        )

    [from] => Array
        (
            [0] => Bangalore
        )

请帮我解决这个问题

2 个答案:

答案 0 :(得分:1)

我会使用array_walk然后使用array_filter然后使用array_values来重置索引。

例如:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Http } from '@angular/http'; //https://stackoverflow.com/questions/43609853/angular-4-and-ionic-3-no-provider-for-http

@Component({
 selector: 'page-register',
 templateUrl: 'register.html'
})

export class RegisterPage {
 data:any = {};

 constructor(public navCtrl: NavController, public http: Http) {
 this.data.username = '';
 this.data.response = '';

 this.http = http;
 }

 submit() {
 var link = 'http://127.0.0.1:777/api/user';
 var myData = JSON.stringify({username: this.data.username});

 this.http.post(link, myData)
 .subscribe(data => {
 this.data.response = data["_body"]; //https://stackoverflow.com/questions/39574305/property-body-does-not-exist-on-type-response
 }, error => {
 console.log("Oooops!");
 });
 }
}

https://3v4l.org/Km1i8

<强>结果:

<?php
$array = [
    'radios1' => [
        'on'
    ],
    'from' => [
        '',
        'Bangalore',
        '',
        '',
    ]
];

array_walk($array, function (&$value, $key) {
    $value = array_values(array_filter($value));
});

print_r($array);

答案 1 :(得分:0)

您的编码尝试表明您希望使用array_filter()在每个子数组上的默认行为,删除所有空的,虚假的,类似于零的值,然后重新索引这些子数组,然后删除所有没有子级的第一级数组,方法是再次致电array_filter()

当函数式编程提供一种简洁的方法时,它在闭包内部采用了迭代函数调用,因此比使用语言构造进行迭代要昂贵。

以下内容提供了相同的功能,而无需任何函数调用,并且不需要重新索引子数组,因为保留值在推入结果数组时会被索引。

代码:(Demo

$array = [
    'radios1' => [
        'on',
    ],
    'empty' => [
        '',
        false,
    ],
    'from' => [
        '',
        'Bangalore',
        null,
        0,
    ]
];

$result = [];
foreach ($array as $key => $items) {
    foreach ($items as $item) {
        if ($item) {
            $result[$key][] = $item;
        }
    }
}

var_export($result);

输出:

array (
  'radios1' => 
  array (
    0 => 'on',
  ),
  'from' => 
  array (
    0 => 'Bangalore',
  ),
)

对于想要删除空格和null但保留零(整数或字符串类型)的任何人,请在条件中使用strlen($item)

相关问题