为什么array_combine没有返回数组?

时间:2016-11-06 02:37:11

标签: php arrays

当我尝试打印从此函数返回的数组时,我得到一个空白屏幕。

我的数组$terms$definitions的长度相同,并且在我致电make_associative_array()之前和之后都存在。

function make_associative_array() {
    return array_combine($terms, $definitions);
}

$c = make_associative_array();
print_r($c);

$术语:

Array ( 
     [0] => Nock (verb) [1] => End [2] => Serving [3] => Nock (noun) 
)

$定义:

Array ( 
     [0] => To place an arrow against the string prior to shooting. [1] => A group of arrows shot during a tournament. Usually 6. [2] => Thread wound around a bow string to protect the string. [3] => A notch at the rear of an arrow. The bow string is placed in the nock. 
)

我使用的是PHP 5.6.27

2 个答案:

答案 0 :(得分:1)

在您的情况下,array_combine会返回NULL,因为$terms和& $definitions范围内的make_associative_array为空。

您可以将它们设为全局:

function make_associative_array() {
    global $terms, $definitions;
    return array_combine($terms, $definitions);
}

或者将它们传递给函数:

function make_associative_array($terms, $definitions) {
    return array_combine($terms, $definitions);
}
$c = make_associative_array($terms, $definitions);

无论如何 - 我真的建议你打开错误:
http://sandbox.onlinephpfunctions.com/code/40cfd2d197aebd4d935c793c1ea662cab50ce8b1

答案 1 :(得分:1)

您必须将参数传递给函数

 <?php
    function make_associative_array($terms,$definitions) {

        return array_combine($terms, $definitions);
    }

    $terms=Array ( 0 => 'Nock (verb)', 1 => 'End', 2=> 'Serving', 3=> 'Nock (noun) '
    );

    $definitions=Array ( 
         0 => 'To place an arrow against the string prior to shooting.' ,1 => 'A group of arrows shot during a tournament. Usually 6.', 2 => 'Thread wound around a bow string to protect the string.' ,3=> 'A notch at the rear of an arrow. The bow string is placed in the nock.' 
    );

    $c = make_associative_array($terms,$definitions);
    echo "<pre>";
    print_r($c);

输出

Array
(
    [Nock (verb)] => To place an arrow against the string prior to shooting.
    [End] => A group of arrows shot during a tournament. Usually 6.
    [Serving] => Thread wound around a bow string to protect the string.
    [Nock (noun) ] => A notch at the rear of an arrow. The bow string is placed in the nock.
)