$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
只需使用 foreach!
foreach($test['test1'] as $key => $value){
echo "$key = $value";
}
如果您必须推送新值,您可以这样做:
$test['test1']['newkey1'] = 'newvalue1';
$test['test1']['newkey2'] = 'newvalue2';
$test['test1']['d'] = '4';
或者
$test['test2'] = array(...);
你可以使用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"
}