简体   繁体   English

函数中的 array_filter 函数

[英]array_filter function in function

I have this function, where a array_filter function is included:我有这个函数,其中包含一个 array_filter 函数:

$var = "test";

function mainFunction() {
    
    global $var;
    
    $myNewArray = array();
    
    $data = array("a", "b", "c");
    
    array_filter($data, function ($value) {
            
        global $myNewArray;
            
        $myNewArray[] = $value;
        
    });

   print_r($myNewArray); // TEST OUTPUT

}

mainFunction();

Problem: My test output myNewArray is empty.问题:我的测试输出 myNewArray 是空的。

I know that my array_filter function is senless at the moment until I check no values.我知道我的 array_filter 函数目前是无意义的,直到我不检查任何值。 But only for testing, I would like to use it, to create a newArray.但仅用于测试,我想使用它来创建一个 newArray。 But this doesn't work.但这不起作用。 Where is my mistake?我的错误在哪里?

UPDATE I updated my code:更新我更新了我的代码:

function mainFunction() {
    
    global $var;
    
    $myNewArray = array();

    $data[] = array("id" => "1", "content" => "Hello");
    $data[] = array("id" => "2", "content" => "World");
    
    $myNewArray = array_filter($data, function ($value) {
        
        if ($value['content'] == "World") {
            return $value['content'];
        }

    });

  print_r($myNewArray); // TEST OUTPUT

}


mainFunction();

This works, but not correctly.这有效,但不正确。 I would like to save only the content value.我只想保存内容值。

But my $myNewArray looks like this:但是我的 $myNewArray 看起来像这样:

Array
(
    [0] => Array
         (
             [id] => 2
             [content] => World
         )
)

Instead of代替

Array
(
    [0] => Array
        (
            [content] => World
        )
)

I would combine array_filter and array_map for this.我会为此结合array_filterarray_map

$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");

// filter the data
$data = array_filter($data, fn ($value) => $value['content'] === 'World');

// map the data
$data = array_map(fn ($value)  => ['content' => $value['content']], $data);

// reset indexes
$data = array_values($data);

print_r($data);

Example: https://phpize.online/s/9U示例: https ://phpize.online/s/9U

In mainFunction you are not using $myNewArray as global so it's only in the scope, but in the array_filter function you are using global $myNewArray;mainFunction中,您没有将$myNewArray用作全局变量,因此它仅在范围内,但在array_filter函数中,您使用的是global $myNewArray;

$var = "test";
$myNewArray; // global array
function mainFunction() {
    global $var, $myNewArray;//if this is not present it's not global $myNewArray
    $myNewArray = array();
    $data = array("a", "b", "c");
    array_filter($data, function ($value) {
        global $myNewArray;//this uses global 
        $myNewArray[] = $value;
    });
    print_r($myNewArray); // TEST OUTPUT
}
mainFunction();

Here is an example of you code without global $myNewArray这是一个没有全局$myNewArray的代码示例

$var = "test";    
function mainFunction($var) {
    $myNewArray = array();
    $data = array("a", "b", "c");
    $myNewArray[] = array_filter($data, function ($value) {
        return $value;
    });
    print_r($myNewArray); // TEST OUTPUT
}

mainFunction($var);

Answer to Update: You can use array_reduce to achieve that更新答案:您可以使用array_reduce来实现

function mainFunction() {
    global $var;
    $myNewArray = array();
    $data[] = array("id" => "1", "content" => "Hello");
    $data[] = array("id" => "2", "content" => "World");
    $myNewArray = array_reduce($data, function($accumulator, $item) {
        if ($item['content'] === "World") 
            $accumulator[] = ['content' => $item['content']];        
        return $accumulator;
    });
    print_r($myNewArray); // TEST OUTPUT
}

mainFunction();

Everything seems to work fine.一切似乎都很好。

<?php

$data = [];
$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");

$filtered_data = array_filter($data, function($value) {
  return $value['content'] == "World";
});

print_r($filtered_data);

The output is just like expected:输出就像预期的那样:

Array ( [1] => Array ( [id] => 2 [content] => World ) )数组([1] => 数组([id] => 2 [内容] => 世界))

But if you want to leave only some fields in resulting array, array_filter will not help you (at least without a crutch) .但是如果你只想在结果数组中保留一些字段, array_filter将无济于事(至少没有拐杖)
You may want to iterate source array and filter it by yourself.您可能想要迭代源数组并自行过滤它。

<?php

$data = [];
$data[] = array("id" => "1", "content" => "Hello");
$data[] = array("id" => "2", "content" => "World");

$filtered_data = [];
foreach($data as $v) {
  if($v['content'] == "World")
    $filtered_data[] = ["content" => $v['content']];
}

print_r($filtered_data);

The output then would be:那么输出将是:

Array ( [0] => Array ( [content] => World ) )数组([0] => 数组([内容] => 世界))

You want two different things:你想要两个不同的东西:

  • filter your array (keep only some elements)过滤你的数组(只保留一些元素)
  • map your array (change the value of each element)映射您的数组(更改每个元素的值)

Filter your array过滤你的数组

On your second attempt you've done it right but array_filter callback function expect a boolean as the return value.在你第二次尝试时,你做对了,但是array_filter回调函数期望一个boolean作为返回值。 It will determine wherever array_filter need to keep the value or not.它将确定array_filter需要在何处保留该值。

Map your array映射您的阵列

You need to remove all value on each element except the "content" value.您需要删除除"content"值之外的每个元素的所有值。 You can use array_map to do that.您可以使用array_map来做到这一点。

function mainFunction() {
    $data[] = array("id" => "1", "content" => "Hello");
    $data[] = array("id" => "2", "content" => "World");
    
    $myNewArray = array_filter($data, function ($value) {
        if ($value['content'] == 'World') {
            return true;
        }
        return false;
    });
    // myNewArray contains now the willing elements, but still don't have the willing format
    /* myNewArray is [
        0 => [
            'id' => '2',
            'content' => 'World'
        ]
    ]*/
    
    $myNewArray = array_map($myNewArray, function($value){
        return [
            'content' => $value['content']
        ];
    });
    // myNewArray contains now the willing elements with the willing format
    /* myNewArray is [
        0 => [
            'content' => 'World'
        ]
    ] */

}


mainFunction();

you can use this code..........你可以使用这段代码.........

<?php
    function test_odd($var)
      {
      return($var & 1);
      }
    
    $a1=array(1,3,2,3,4);
    print_r(array_filter($a1,"test_odd"));
    ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM