PHP将混合顺序和关联数组转换为关联数组

时间:2018-04-24 23:38:14

标签: php arrays sequential associative

我想仅从$ initial构建$ goal数组。有任何想法吗?谢谢

编辑:问题可能是如何区分关联部分和顺序部分。

$intial=[
    "one",
    "two"=>"myTwo",
    "three",
    "four"=>"myFour"
];
$goal=[
    "one"=>null,
    "two"=>"myTwo",
    "three"=>null,
    "four"=>"myFour"
];

2 个答案:

答案 0 :(得分:1)

'顺序'部分将包含数字键,因此如果您的'关联'键始终是字符串,您可以使用它来区分:

$goal = [];
foreach ($initial as $key => $value) {
    if (is_numeric($key)) {
        $goal[$value] = null;
    } else {
        $goal[$key] = $value;
    }
}

答案 1 :(得分:0)

int reached = 0;

private void fillStackToAlmostDead() {
    for (int i = 0; i < 10; i++)
        try {
            reached = 0;
            exhausting(-1, null);
        } catch (StackOverflowError e) {
            System.out.println(String.format("Filled with %d calls", reached));
        }
}

private void exhausting(int depth, Callable after) {
    if (depth < 0)
        reached += 1;

    if (depth != 0)
        exhausting(depth - 1, after);
}