php - 如何将最后一个数组值更改为第三个位置?
问题描述
阵列位置是否有任何可能的变化?
我有类似的数组
[files] => Array
(
[name] => Array
(
[0] => file 1
[1] => file 2
[2] => file 3
)
[size] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[error] => Array
(
[0] => abc
[1] => def
[2] => ghi
)
[position] => Array
(
[0] => left
[1] => right
[2] => center
)
[details] => Array
(
[0] => detail1
[1] => detail2
[2] => detail3
)
)
我希望数组值“详细信息”移动到错误前大小旁边的第三个位置。可以通过PHP吗??
解决方案
是的,有可能,曾经有一段时间我更喜欢使用这样的东西。看看下面的函数,它会做你想要的:
/** Easily append anywhere in associative arrays
* @param array $arr Array to insert new values to
* @param string|int $index Index to insert new values before or after
* @param array $value New values to insert into the array
* @param boolean $afterKey Insert new values after the $index key
* @param boolean $appendOnFail If key is not present, append $value to tail of the array
* @return array
*/
function arrayInsert($arr, $index, $value, $afterKey = true, $appendOnFail = false) {
if(!isset($arr[$index])) {
if($appendOnFail) {
return $arr + $value;
} else {
echo "arrayInsert warning: index `{$index}` does not exist in array.";
return $arr;
}
} else {
$index = array_search($index, array_keys($arr)) + intval($afterKey);
$head = array_splice($arr, $index);
return $arr + $value + $head;
}
}
示例结果:
>>> $test = ['name'=>[], 'size'=>[], 'error'=>[], 'position'=>[], 'details'=>[]];
=> [
"name" => [],
"size" => [],
"error" => [],
"position" => [],
"details" => [],
]
>>> arrayInsert($test, 'size', ['details'=>$test['details']]);
=> [
"name" => [],
"size" => [],
"details" => [],
"error" => [],
"position" => [],
]
推荐阅读
- r - 向 ggplots 添加图层有效,但在循环中添加无效
- javascript - Javascript 数据使用 ajax nad 消息 400 发送到 python 烧瓶 - 错误请求
- .net-core - 如何使用 dot net core 构建跨平台 gui 应用程序?
- angular - 如何在子组件中模拟 NGXS 选择?
- apache - Apache 2.4 中不允许 PUT 和 DELETE 请求
- esp32 - TTGO LoRa32 不带 OLED 显示屏
- pytorch - 如何从上次中断的事件中使用 torch.utils.tensorboard.SummaryWriter
- many-to-many - 另一个多对多维度的雪花模式
- java-stream - 在 pogo 类中使用流 api 查找元素
- javascript - 如何在 TinyMCE 中修改注释中的属性