PHP键值数组推送

时间:2013-07-28 12:22:38

标签: php arrays key-value

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

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

5 个答案:

答案 0 :(得分:0)

您没有指定要推送您的值。

// 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”。如果您想要不同的输出,请回复您想要的输出。

答案 1 :(得分:0)

您可以使用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

答案 2 :(得分:-1)

只需使用foreach!

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

答案 3 :(得分:-1)

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

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

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

答案 4 :(得分:-1)

你可以使用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"
}