php - 阵列翻转碰撞问题

标签 php arrays

有没有我不知道的函数/方法可以避免在翻转数组时删除类似的键。示例如下:

原始数组:

Array ( [last_modified] => input [published] => input [project_content] => textarea ) 

使用数组翻转(键冲突):

Array ( [input] => published [textarea] => project_content )

最佳答案

如果你想保留你的 key ,你可以有一个二维数组:

<?php
$arr = array ( 'last_modified' => 'input', 'published' => 'input', 'project_content' => 'textarea' );
$result = array();
foreach($arr as $k => $v) {
    if (array_key_exists($v, $result)) {
        $result[$v][] = $k;
    } else {
        $result[$v] = array($k);        
    }
}
print_r($result);
?>

This will print out:

Array
(
    [input] => Array
        (
            [0] => last_modified
            [1] => published
        )

    [textarea] => Array
        (
            [0] => project_content
        )

)

关于php - 阵列翻转碰撞问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18091481/

相关文章:

c++ - 内存中的多维数组

c - 如何不使用队列,堆栈或数组来解决此问题?

arrays - swift 遵循 Stridable 后进入死循环

php - 在php中删除带有br标签的p标签

php - 尝试在另一个类 var 的数组中使用静态 var 时出错

php - Google map 显示空白蓝屏

c++ - 从 std::array 获取对原始数组的引用

php header() 无法在 ssl 网站上运行

php - 如何在 symfony 2 php 中访问注释中的类变量和常量

javascript - 使用 JavaScript 映射键/值