在进入循环之前将函数应用于foreach中的值

时间:2018-02-15 15:18:29

标签: php

我认为这根本不可能,但希望我被证明是错误的。

我想实现其中一个" does not work"从下面的行:

<?php
// Note, this is purposely an overly simplistic example

// Pretend that I do not control this array and it is
// provided to me from the database or an API or something
$data_array = [
    ' a ',
    ' b ',
    ' c '
];

$new_array = [];

// Apply a function call before entering the loop
// foreach( $array as trim( $v ) ) // does not work
// foreach( $array as $v = trim( $v ) ) // does not work
foreach( $data_array as $v ) // works but I don't want this
{
    $v = trim( $v ); // works but I don't want this
    $new_array[ $v ] = $v;
}

var_dump( $new_array );

输出:

array(3) {
  ["a"]=>
  string(1) "a"
  ["b"]=>
  string(1) "b"
  ["c"]=>
  string(1) "c"
}

2 个答案:

答案 0 :(得分:1)

简单并且只使用一个参数的函数:

foreach(array_map('trim', $array) as $v) {
    $array[$v] = $v;
}

但是,要实现没有整数键的新字符串键,您需要unset它:

foreach(array_map('trim', $array) as $k => $v) {
    unset($array[$k]);
    $array[$v] = $v;
}

循环的替代:

$array = array_combine($v = array_map('trim', $array), $v);

要通过引用实际修改值,您需要重新分配数组:

foreach($array = array_map('trim', $array) as &$v) {
    $v = $v.' woo!';
}

所有这些,您已经展示了实现结果的最有效和最可读的方式:

foreach($array as $v) {
    $v = trim($v);
    $array[$v] = $v;
}

答案 1 :(得分:0)

$str = " a , b , c ";
$array = [];

// note the space around commas, 
// you can explode by that string instead of trim
foreach(explode(' , ', $str) as $v) {
    $array[$v] = $v;
}

var_dump($array);

如果有多个空格,您还可以在转到for循环之前执行str_replace

$str = str_replace(' ', '', $str);
foreach(explode(',', $str) as $v) {
    // ...

但是,对于以下类型的字符串,这不会起作用:

$str = "a a , b , c";
// str_replace will result in
// "aa,b,c"

编辑:现在您已更新了问题:

$array = [
    ' a ',
    ' b ',
    ' c '
];

$array  = array_map('trim', $array);
$result = array_combine($array, $array);

var_dump($array);