简体   繁体   English

在自定义函数内,将值推入foreach循环内的多维数组

[英]Push value to multidimensional array within a foreach loop, inside a custom function

When using a foreach loop it works with no issues, but I don't know how to implement this inside a function. 使用foreach循环时,它没有问题,但我不知道如何在函数中实现此功能。

The function I'm trying to write. 我正在尝试编写的功能。

function fgf($array, $section_k, $section_n) {
    foreach($array as &$k_687d) {
        $k_687d['section']      = section_k;
        $k_687d['section_name'] = $section_n;
        $k_687d['section_ssn']  = 'df6s';
    }
    return $array;
}

The Array Example. 数组示例。

$array = array(
    'work'=>array(
        'default'  => 1, 
        'opt_type' => 'input',
    ),
    'something_else' => array(
        'default'  => 1, 
        'opt_type' => 'list',
    ),
)

CALL 呼叫

fgf($array, 'work_stuff', 'Work Stuff');

I think you intended something like 我想你打算像

function fgf($array, $section_k, $section_n)
{
    $newArray = [];            

    for($i = 0, $count = count($array); $i <= $count; $i++) {
        $newArray[$i]['section']      = $section_k;
        $newArray[$i]['section_name'] = $section_n;
        $newArray[$i]['section_ssn']  = 'df6s';
    }

    return $newArray;
}

Then you may call it assigning the resulting array to a variable 然后可以调用它,将结果数组分配给变量

$newArray = fgf($array, 'work_stuff', 'Work Stuff');

You have missed $ : 您错过了$

$k_687d['section']      = $section_k;
                          ^

And if you want the original array to be modified, pass the array as reference otherwise assign your calling function to a variable. 并且,如果您要修改原始数组,请将该数组作为引用传递,否则将调用函数分配给变量。

You're not using your return value, so your $array variable stays unaltered. 您没有使用返回值,因此$array变量保持不变。

You should either assign the return value of your function to the variable, eg.: 您应该将函数的返回值分配给变量,例如:

$array = fgf($array, 'work_stuff', 'Work Stuff');

or use "Pass by reference": 或使用“通过引用传递”:

function fgf(&$array, $section_k, $section_n)

(notice the ampersand before the $array argument). (请在$array参数前注意“&”号)。 In this case you can remove the return-statement from your function. 在这种情况下,您可以从函数中删除返回语句。 See: http://php.net/manual/en/language.references.pass.php 参见: http : //php.net/manual/en/language.references.pass.php

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

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