PHP 键值数组推送


PHP key-value array push

$test = array (
    "test1"  => array("a" => "1", "b" => "2", "c" => "3")
);

我有一个像上面这样的数组。ı 想要在循环中推送其值。怎么可能?你能告诉我吗?

您没有指定要将值推送到哪个值。

// array to push content
$newArray = array();
// loop through first dimensional of your array
foreach ($test as $key => $hash) {
    // your hash is also an array, so again a loop through it
    foreach ($hash as $innerkey => $innerhash) {
        array_push($newArray, $innerhash);
    }
}

数组将仅包含"1"、"2"、"3"。如果您想要不同的输出,请回复您想要的输出。

您可以使用array_push()函数来推送数组中的元素。 array_push() 将数组视为堆栈,并将传递的变量推送到数组的末尾。数组的长度随着推送的变量数而增加。

$test = array (
    "test1"  => array("a" => "1", "b" => "2", "c" => "3")
);
$test[] = "YOUR ELEMENT";
or
array_push($test, 'YOUR DATA', 'ANOTHER DATA');

/* If you use array_push() to add one element to the array it's better to use
$array[] = because in that way there is no overhead of calling a function. 
array_push() will raise a warning if the first argument is not an array. 
This differs from the $var[] behaviour where a new array is created. */

函数参考:http://php.net/manual/en/function.array-push.php

如果你必须推送新值,你可以这样做:

$test['test1']['newkey1'] = 'newvalue1';
$test['test1']['newkey2'] = 'newvalue2';
$test['test1']['d'] = '4';

$test['test2'] = array(...);

只要用foreach!

foreach($test['test1'] as $key => $value){
    echo "$key = $value";
}

你可以使用 foreach。

foreach ($test as $key => $value) // Loop 1 times
{
    // $key equals to "test1"
    // $value equals to the corespondig inner array
    foreach ($value as $subkey => $subvalue) // Loop 3 times
    {
        // first time $subkey equals to "a"
        // first time $subvalue equals to "1"
        // .. and so on
    }
}

如果您期望第一个子数组只有一个作为示例,则可以跳过第一个循环:

foreach ($test["test1"] as $subkey => $subvalue) // Loop 3 times
{
    // first time $subkey equals to "a"
    // first time $subvalue equals to "1"
    // .. and so on
}

编辑:如果要将数据推送到内部,则不能将局部变量用作$key和$value。您可以使用$key引用原始数组变量。例如:

foreach ($test["test1"] as $subkey => $subvalue) // Loop 3 times
{
    // changing current value
    $test["test1"][$subkey] = "new value";
    // pushing new member
    $test["test1"][] = "some value"
}