$test = array (
"test1" => array("a" => "1", "b" => "2", "c" => "3")
);
I have an array like above. ı want to push its values in a loop. How can it be possible ? Could you please tell me ?
$test = array (
"test1" => array("a" => "1", "b" => "2", "c" => "3")
);
I have an array like above. ı want to push its values in a loop. How can it be possible ? Could you please tell me ?
You didn't have specified to which you want to push your values.
// 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);
}
}
the array will contain only "1", "2", "3". If you want a different output, please reply which output you want.
You can use array_push()
function to push the elements in an array. array_push()
treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed.
$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. */
Function Reference: http://php.net/manual/en/function.array-push.php
Just use foreach!
foreach($test['test1'] as $key => $value){
echo "$key = $value";
}
If you have to push new values you can just do like this:
$test['test1']['newkey1'] = 'newvalue1';
$test['test1']['newkey2'] = 'newvalue2';
$test['test1']['d'] = '4';
or
$test['test2'] = array(...);
You can use 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
}
}
If you are expecting the first subarray to be only one as your example you can skip the first loop:
foreach ($test["test1"] as $subkey => $subvalue) // Loop 3 times
{
// first time $subkey equals to "a"
// first time $subvalue equals to "1"
// .. and so on
}
Edit: If you want to push data inside you can't use the local variables as $key and $value. You can use $key to reffer the original array variable. For example:
foreach ($test["test1"] as $subkey => $subvalue) // Loop 3 times
{
// changing current value
$test["test1"][$subkey] = "new value";
// pushing new member
$test["test1"][] = "some value"
}