当前位置: 首页 > news >正文

PHP 数组 如何移动某个元素到某个元素前面

PHP 数组元素移动实现

以下是几种将数组元素移动到指定元素前面的实现方法:

方法1:使用数组切片和拼接

/*** 将指定元素移动到目标元素前面* * @param array $array 要操作的数组* @param mixed $source 要移动的元素(值或键)* @param mixed $target 目标元素(值或键)* @param bool $byKey 是否使用键来定位元素* @return array 处理后的数组*/
function moveElementBefore(array $array, $source, $target, bool $byKey = false): array
{// 获取源元素和目标元素的键$sourceKey = $byKey ? $source : array_search($source, $array, true);$targetKey = $byKey ? $target : array_search($target, $array, true);// 如果任一元素不存在,返回原数组if ($sourceKey === false || $targetKey === false) {return $array;}// 如果源元素已经在目标元素前面,不需要移动if (array_search($sourceKey, array_keys($array)) < array_search($targetKey, array_keys($array))) {return $array;}// 提取源元素$sourceValue = $array[$sourceKey];unset($array[$sourceKey]);// 重新构建数组$result = [];foreach ($array as $key => $value) {if ($key === $targetKey) {$result[$sourceKey] = $sourceValue;}$result[$key] = $value;}return $result;
}

方法2:使用 array_splice 函数

/*** 使用 array_splice 移动元素* * @param array $array 要操作的数组* @param mixed $source 要移动的元素值* @param mixed $target 目标元素值* @return array 处理后的数组*/
function moveElementBeforeWithSplice(array $array, $source, $target): array
{// 查找元素位置$sourceIndex = array_search($source, $array, true);$targetIndex = array_search($target, $array, true);// 如果任一元素不存在,返回原数组if ($sourceIndex === false || $targetIndex === false) {return $array;}// 如果源元素已经在目标元素前面,不需要移动if ($sourceIndex < $targetIndex) {return $array;}// 提取源元素$sourceValue = $array[$sourceIndex];// 使用 array_splice 移除源元素array_splice($array, $sourceIndex, 1);// 插入到目标位置array_splice($array, $targetIndex, 0, [$sourceValue]);return $array;
}

方法3:处理关联数组

/*** 移动关联数组中的元素* * @param array $array 关联数组* @param mixed $sourceKey 要移动的元素的键* @param mixed $targetKey 目标元素的键* @return array 处理后的数组*/
function moveAssocElementBefore(array $array, $sourceKey, $targetKey): array
{// 检查键是否存在if (!array_key_exists($sourceKey, $array) || !array_key_exists($targetKey, $array)) {return $array;}// 获取源元素值$sourceValue = $array[$sourceKey];// 移除源元素unset($array[$sourceKey]);// 重新构建数组$result = [];foreach ($array as $key => $value) {if ($key === $targetKey) {$result[$sourceKey] = $sourceValue;}$result[$key] = $value;}return $result;
}

方法4:使用回调函数定位元素

/*** 使用回调函数定位要移动的元素和目标元素* * @param array $array 要操作的数组* @param callable $sourceFinder 用于定位源元素的回调函数* @param callable $targetFinder 用于定位目标元素的回调函数* @return array 处理后的数组*/
function moveElementBeforeWithCallback(array $array, callable $sourceFinder, callable $targetFinder): array
{// 查找源元素和目标元素$sourceKey = null;$targetKey = null;foreach ($array as $key => $value) {if ($sourceFinder($value, $key) && $sourceKey === null) {$sourceKey = $key;}if ($targetFinder($value, $key) && $targetKey === null) {$targetKey = $key;}}// 如果任一元素不存在,返回原数组if ($sourceKey === null || $targetKey === null) {return $array;}// 获取源元素值$sourceValue = $array[$sourceKey];// 移除源元素unset($array[$sourceKey]);// 重新构建数组$result = [];foreach ($array as $key => $value) {if ($key === $targetKey) {$result[$sourceKey] = $sourceValue;}$result[$key] = $value;}return $result;
}

使用示例

// 示例1:移动数值数组中的元素
$numbers = [1, 2, 3, 4, 5];
echo "原始数组: " . implode(', ', $numbers) . "\n";// 将数字3移动到数字2前面
$numbers = moveElementBefore($numbers, 3, 2);
echo "移动后数组: " . implode(', ', $numbers) . "\n";
// 输出: 1, 3, 2, 4, 5// 示例2:移动关联数组中的元素
$users = ['alice' => ['age' => 25, 'role' => 'user'],'bob' => ['age' => 30, 'role' => 'admin'],'charlie' => ['age' => 35, 'role' => 'user'],
];
echo "原始用户数组:\n";
print_r($users);// 将bob移动到charlie前面
$users = moveAssocElementBefore($users, 'bob', 'charlie');
echo "移动后用户数组:\n";
print_r($users);// 示例3:使用回调函数定位元素
$products = [['id' => 1, 'name' => 'Laptop', 'price' => 1000],['id' => 2, 'name' => 'Mouse', 'price' => 20],['id' => 3, 'name' => 'Keyboard', 'price' => 50],
];// 将价格大于100的产品移动到鼠标前面
$products = moveElementBeforeWithCallback($products,function($item) { return $item['price'] > 100; }, // 源元素条件:价格大于100function($item) { return $item['name'] === 'Mouse'; } // 目标元素条件:名称为Mouse
);echo "移动后产品数组:\n";
print_r($products);

性能优化版本

对于大型数组,可以使用更高效的方法:

/*** 高效移动数组元素* * @param array $array 要操作的数组* @param mixed $source 要移动的元素值* @param mixed $target 目标元素值* @return array 处理后的数组*/
function moveElementBeforeEfficient(array $array, $source, $target): array
{// 获取所有键$keys = array_keys($array);$values = array_values($array);// 查找元素位置$sourceIndex = array_search($source, $values, true);$targetIndex = array_search($target, $values, true);// 如果任一元素不存在,返回原数组if ($sourceIndex === false || $targetIndex === false) {return $array;}// 如果源元素已经在目标元素前面,不需要移动if ($sourceIndex < $targetIndex) {return $array;}// 提取源元素$sourceKey = $keys[$sourceIndex];$sourceValue = $values[$sourceIndex];// 创建新数组$result = [];$targetReached = false;for ($i = 0; $i < count($values); $i++) {if ($i === $targetIndex && !$targetReached) {$result[$sourceKey] = $sourceValue;$targetReached = true;}if ($i !== $sourceIndex) {$result[$keys[$i]] = $values[$i];}}return $result;
}

处理多维数组

/*** 移动多维数组中的元素* * @param array $array 多维数组* @param string $keyField 用于比较的键字段* @param mixed $sourceValue 源元素键字段的值* @param mixed $targetValue 目标元素键字段的值* @return array 处理后的数组*/
function moveMultiDimensionalElementBefore(array $array, string $keyField, $sourceValue, $targetValue): array
{// 查找元素位置$sourceIndex = null;$targetIndex = null;foreach ($array as $index => $item) {if ($item[$keyField] === $sourceValue && $sourceIndex === null) {$sourceIndex = $index;}if ($item[$keyField] === $targetValue && $targetIndex === null) {$targetIndex = $index;}}// 如果任一元素不存在,返回原数组if ($sourceIndex === null || $targetIndex === null) {return $array;}// 提取源元素$sourceElement = $array[$sourceIndex];// 移除源元素unset($array[$sourceIndex]);// 重新构建数组$result = [];$currentIndex = 0;foreach ($array as $index => $item) {if ($currentIndex === $targetIndex) {$result[] = $sourceElement;}$result[] = $item;$currentIndex++;}return $result;
}

使用示例

// 示例:移动多维数组中的元素
$employees = [['id' => 1, 'name' => 'Alice', 'department' => 'HR'],['id' => 2, 'name' => 'Bob', 'department' => 'IT'],['id' => 3, 'name' => 'Charlie', 'department' => 'Finance'],
];// 将Bob移动到Charlie前面
$employees = moveMultiDimensionalElementBefore($employees, 'name', 'Bob', 'Charlie');
print_r($employees);

这些实现提供了多种方法来移动数组元素,您可以根据具体需求选择合适的方法。

对于简单数组,使用方法1或2;

对于关联数组,使用方法3;

对于复杂条件,使用方法4。

http://www.dtcms.com/a/427410.html

相关文章:

  • RynnVLA-001:利用人类演示来改进机器人操作
  • Linux操作系统课问题总结:从/proc目录到磁盘管理
  • Honeywell SS360NT磁性位置传感器—扫地机器人
  • 百度站长工具seo查询云南网页设计制作
  • php网站优点深圳市福田区
  • 开源代码uSNMP推荐
  • 鸿蒙:获取屏幕的刷新率、分辨率、监听截屏或录屏状态等
  • Springboot城市空气质量数据管理系统futcv(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
  • 开发一个网站的费用两学一做11月答题网站
  • 微信小程序入门学习教程,从入门到精通,微信小程序常用API(上)——知识点详解 + 案例实战(4)
  • UNIX下C语言编程与实践14-UNIX 文件系统格式化:磁盘分区与文件系统创建原理
  • UNIX下C语言编程与实践16-UNIX 磁盘空间划分:引导块、超级块、i 节点区、数据区的功能解析
  • 互联网兼职做网站维护做ui设计用什么素材网站
  • ETL参数化技巧:如何避免写一堆重复任务?
  • git下载分支
  • Linux应用开发·Makefile菜鸟教程
  • ai智能化算法
  • 【专业词典】冰山模型
  • 第三方应用测试:【移动应用后端API自动化测试:Postman与Newman的集成】
  • 企业网站备案 淘宝客前端工程师主要做什么
  • 桌面预测类开发,桌面%雷达,信号预测%系统开发,基于python,tk,scikit-learn机器学习算法实现,桌面预支持向量机分类算法,CSV无数据库
  • 网站备案黑名单重庆新闻头条24小时
  • 使用vscode的ssh功能连接远程服务器卡在Setting up SSH Host IP: Downloading VS Code Server的解决方案
  • vscode连接算力平台
  • VSCode中Java开发环境配置的三个层级(Windows版)1-3
  • 西安建设网站的公司网页装修设计
  • 太空算力革命:卫星如何成为地面交通的“天脑“
  • 大数据 Python小说数据分析平台 小说网数据爬取分析系统 Django框架 requests爬虫 Echarts图表 17k小说网 (源码)✅
  • 第 1 天:零基础入门 C 语言 —— 认识 C 语言的起源、特点与应用场景
  • 网站建设制作公司地址网站建设费用明细