如何向多维数组添加当前添加项的索引号?
$data_array[] = array('data_array_index' => *the index number of the this array on $data_array*, 'stuff' => 'stuff', etc.)
所以当我:
print_r($data_array);
Array(
[0] => Array(
data_array_index => 0
stuff => stuff
)
[25] => Array(
data_array_index => 25
stuff => stuff
)
etc.
谢谢
修改
这应该有用吗?
$data_array[] = array('data_array_index' => end($data_array)+1, 'stuff' => 'stuff', etc.)
答案 0 :(得分:1)
你可以这样做:
$array = [
0 => [ "data_array_index" => 0, "stuff" => "stuff" ],
25 => [ "data_array_index" => 25, "stuff" => "stuff" ]
];
$array[] = array('data_array_index' => 0, 'stuff' => 'stuff')
end($array);
$last_id = key($array);
$array[$last_id]['data_array_index'] = $last_id;
我不知道你为什么要在数组中data_array_index
,因为如果你把它放在foreach
循环中,你就可以得到密钥而不需要变量。
示例:
foreach($key => $data) {
^^^^ The same as `data_array_index`
}
答案 1 :(得分:0)
假设你有这个数组:
$data_array = [
0 => [ "data_array_index" => 0, "stuff" => "stuff" ],
25 => [ "data_array_index" => 25, "stuff" => "stuff" ]
];
现在设置一个键(注意$data_array[100]
):
$data_array[100] = [ "data_array_index" => 100, "stuff" => "stuff" ];
答案 2 :(得分:0)
尝试一次
$arr=array(12=>array("stuff"=>"stuff1"),15=>array("stuff"=>"stuff2"));
foreach($arr as $key=>$val){
$arr[$key]['data_array_index']=$key;
}
echo "<pre>"; print_r($arr);
答案 3 :(得分:0)
使用array_walk
array_walk($data_array,function($value,$key)use($new_array) {
$value['data_array_index'] = $key;
$new_array[$key]=$value;
});
答案 4 :(得分:0)
对于我的解决方案,请参阅下面的代码。请注意,这是一个非常基本的功能。它不提供任何故障安全或后备。如果删除一个键,它将填充空格等。
<?php
// data array
$data_array = [];
// additional info for the array
$info_a = "Lorem Ipsum";
$info_b = "Lorem Ipsum";
// call function
addElement($data_array, $info_a);
addElement($data_array, $info_b);
// display output
echo '<pre>';
print_r($data_array);
echo '</pre>';
function addElement(&$array, $info)
{
// add info to the array
$array[] = [
'stuff'=>$info
];
// get the key of the current array
end($array);
$key = key($array);
// add this information to the array
$array[$key]['data_array_index'] = $key;
}
?>
输出
Array
(
[0] => Array
(
[stuff] => Lorem Ipsum
[data_array_index] => 0
)
[1] => Array
(
[stuff] => Lorem Ipsum
[data_array_index] => 1
)
)