PHP array_filter从数组中仅获取一个值 [英] PHP array_filter to get only one value from an array

查看:223
本文介绍了PHP array_filter从数组中仅获取一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图排除foreach循环,并使用数组函数对其进行重构.我假设下面的代码将为我提供源数组中所有第一项的结果.

I'm trying to exclude foreach-loops and refactor them with array functions. I was under the assumption the code below would give me a result with all first items from the source array.

<?php
    $data= [
        0 => [1, 'test1'],
        1 => [2, 'test2'],
        2 => [3, 'test3'],
    ];

    $ids = array_filter($data, function($item) {
        return $item[0];
    });

    var_dump($ids);

但是当我var_dump $ids时,我得到了输出:

But when I var_dump $ids I get the output:

array (size=3)
  0 => 
    array (size=2)
      0 => int 1
      1 => string 'test1' (length=5)
  1 => 
    array (size=2)
      0 => int 2
      1 => string 'test2' (length=5)
  2 => 
    array (size=2)
      0 => int 3
      1 => string 'test3' (length=5)

为什么没有输出:

array (size=3)
  0 => int 1
  1 => int 2
  2 => int 3

推荐答案

array_filter 用于根据数组元素是否满足特定条件来过滤掉它们.因此,您将创建一个返回true或false的函数,并针对该数组测试数组的每个元素.您的函数将始终返回true,因为每个数组中都有第一个元素,因此该数组不变.

array_filter is used for filtering out elements of an array based on whether they satisfy a certain criterion. So you create a function that returns true or false, and test each element of the array against it. Your function will always return true, since every array has a first element in it, so the array is unchanged.

您正在寻找的是 array_map ,它通过在数组上运行回调来修改数组中的每个元素.

What you're looking for is array_map, which modifies each element in an array by running the callback over it.

<?php
$data= [
    0 => [1, 'test1'],
    1 => [2, 'test2'],
    2 => [3, 'test3'],
];

$ids = array_map(function($item) {
    return $item[0];
}, $data);

var_dump($ids);

这篇关于PHP array_filter从数组中仅获取一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆