note 33609 modified in function.array-splice by vrana
| From: | vrana@php.net | Date: | Tue, 17 Aug 2004 14:49:49 +0000 |
| Subject: | note 33609 modified in function.array-splice by vrana | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-80089@lists.php.net to get a copy of this message | ||
I couldn't get array_splice() to insert into a multidimensional array, so I cribbed this from
the notes for array_push() (a thousand thanks to jhall at jadeinternet dot net). I'm dealing
with a spreadsheet-looking dataset, and it lets me add "rows" where the row data is the
array that I have assigned to $val, and the row number is $ky:
<?php
function insert_into_array($array,$ky,$val)
{
$n = $ky;
foreach($array as $key => $value)
{
$backup_array[$key] = $array[$key];
}
$upper_limit = count($array);
while($n <= $upper_limit)
{
if($n == $ky)
{
$array[$n] = $val;
echo $n;
}
else
{
$i = $n - "1";
$array[$n] = $backup_array[$i];
}
$n++;
}
return $array;
}
?>
So that:
<?php
$list = array( "0" => "zero",
"1" => "one",
"2" => "two",
"3" => "three",
"4" => "four",
"5" => "five",
"6" => "six");
$value = "New Number Three";
$key = "3";
$new = insert_into_array($list,$key, $value);
?>
Will Return:
$list =
Array
(
[0] => zero
[1] => one
[2] => two
[3] => three
[4] => four
[5] => five
[6] => six
)
$new=
Array
(
[0] => zero
[1] => one
[2] => two
[3] => New Number Three
[4] => three
[5] => four
[6] => five
[7] => six
)
--was--
I couldn't get array_splice() to insert into a multidimensional array, so I cribbed this from
the notes for array_push() (a thousand thanks to jhall at jadeinternet dot net). I'm dealing
with a spreadsheet-looking dataset, and it lets me add "rows" where the row data is the
array that I have assigned to $val, and the row number is $ky:
function insert_into_array($array,$ky,$val)
{
$n = $ky;
foreach($array as $key => $value)
{
$backup_array[$key] = $array[$key];
}
$upper_limit = count($array);
while($n <= $upper_limit)
{
if($n == $ky)
{
$array[$n] = $val;
echo $n;
}
else
{
$i = $n - "1";
$array[$n] = $backup_array[$i];
}
$n++;
}
return $array;
}
So that:
$list = array( "0" => "zero",
"1" => "one",
"2" => "two",
"3" => "three",
"4" => "four",
"5" => "five",
"6" => "six");
$value = "New Number Three";
$key = "3";
$new = insert_into_array($list,$key, $value);
Will Return:
$list =
Array
(
[0] => zero
[1] => one
[2] => two
[3] => three
[4] => four
[5] => five
[6] => six
)
$new=
Array
(
[0] => zero
[1] => one
[2] => two
[3] => New Number Three
[4] => three
[5] => four
[6] => five
[7] => six
)
http://php.net/manual/en/function.array-splice.php