我正在尝试做某事,但找不到任何解决方案,我也很难将其放入工作中,因此这里是示例代码,也许足以证明我的目标:

$input = array
(
    'who' => 'me',
    'what' => 'car',
    'more' => 'car',
    'when' => 'today',
);

现在,我想使用 array_splice() 从数组中删除(并返回)一个元素:

$spliced = key(array_splice($input, 2, 1)); // I'm only interested in the key...

以上将删除并返回1个元素(第三个参数) $input (第一个论点),在偏移2(第二个参数),所以 $spliced 将保持价值 more.

我会迭代 $input 有了一个foreach循环,我知道要剪接的钥匙,但问题是我不知道 数值偏移 从那以后 array_splice 只接受我不知道该怎么办的整数。

一个非常乏味的例子:

$result = array();

foreach ($input as $key => $value)
{
    if ($key == 'more')
    {
        // Remove the index "more" from $input and add it to $result.
        $result[] = key(array_splice($input, 2 /* How do I know its 2? */, 1));
    }
}

我首先使用 array_search() 但这是毫无意义的,因为它会返回关联索引。

如何确定关联索引的数值偏移?

有帮助吗?

解决方案

只是抓住 unset提高价值是一种更好的方法(也可能更快), ,但是无论如何,你只能数一数

$result = array();
$idx = 0; // init offset
foreach ($input as $key => $value)
{
    if ($key == 'more')
    {
        // Remove the index "more" from $input and add it to $result.
        $result[] = key(array_splice($input, $idx, 1));
    }
    $idx++; // count offset
}
print_R($result);
print_R($input);

给予

Array
(
    [0] => more
)
Array
(
    [who] => me
    [what] => car
    [when] => today
)

从技术上讲,关联密钥没有数值索引。如果输入数组是

$input = array
(
    'who' => 'me',
    'what' => 'car',
    'more' => 'car',
    'when' => 'today',
    'foo', 'bar', 'baz'
);

然后索引2是“ BAZ”。但由于 array_slice 接受 抵消, ,它与数字键不同,它使用数组中该位置的元素(按照元素出现),这就是为什么沿着工作进行计数的原因。

在旁注上,带有数字键,您会得到有趣的结果,因为您正在测试平等而不是身份。做了 $key === 'more' 而是为了防止“更多”被打字。由于关联键是唯一的,因此在“更多”之后,您也可以返回,因为检查后续键是毫无意义的。但确实:

if(array_key_exists('more', $input)) unset($input['more']);

其他提示

我找到了解决方案:

$offset = array_search('more', array_keys($input)); // 2

即使有“有趣”的阵列,例如:

$input = array
(
    'who' => 'me',
    'what' => 'car',
    'more' => 'car',
    'when' => 'today',
    'foo', 'bar', 'baz'
);

这:

echo '<pre>';
print_r(array_keys($input));
echo '</pre>';

正确输出以下内容:

Array
(
    [0] => who
    [1] => what
    [2] => more
    [3] => when
    [4] => 0
    [5] => 1
    [6] => 2
)

这是一个微不足道的解决方案,但到达那里有些晦涩。

感谢所有人的所有帮助。 =)

$i = 0;
foreach ($input as $key => $value)
{
    if ($key == 'more')
    {
        // Remove the index "more" from $input and add it to $result.
        $result[] = key(array_splice($input, $i , 1));

    }
    $i++;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top