Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:获取数组中的第一个和最后一个元素条目,并将其';钥匙_Php_Arrays - Fatal编程技术网

PHP:获取数组中的第一个和最后一个元素条目,并将其';钥匙

PHP:获取数组中的第一个和最后一个元素条目,并将其';钥匙,php,arrays,Php,Arrays,我目前正在处理一些任务,需要获取元素第一次也是最后一次出现的数组的键 例如: $array = [1,2,3,2,4,1,1,2,3]; getFor(1); // keys 0 and 6 getFor(2); // keys 1 and 7 getFor(3); // keys 2 and 8 如果您能帮我做这件事,我将不胜感激 另外,简单的数组搜索在这里是无效的,因为对于很长的数组(超过1000000个条目)需要花费太多的时间。所以我在寻找一个不明显的解决方案 另外,getFor返回类

我目前正在处理一些任务,需要获取元素第一次也是最后一次出现的数组的键

例如:

$array = [1,2,3,2,4,1,1,2,3];

getFor(1); // keys 0 and 6
getFor(2); // keys 1 and 7
getFor(3); // keys 2 and 8
如果您能帮我做这件事,我将不胜感激

另外,简单的数组搜索在这里是无效的,因为对于很长的数组(超过1000000个条目)需要花费太多的时间。所以我在寻找一个不明显的解决方案

另外,
getFor
返回类型不是必需的,它可以是字符串或两个值的数组


<?php

   $array = array(1,2,3,2,4,1,1,2,3);
   getFor(1,$array);

   function getFor($a,$arr)
   {
     $keys = array_keys($arr, $a);
     $count = count($keys);
     $first = $keys[0];
     $last = $keys[$count-1];
     $str = $first."=".$last;
     echo $str;
   }

?>

这里有一个面向对象的解决方案:

class GetFor
{
    private $Foo[];
    public function __construct(
        array $foo, $bar
    ) {
        $this->Foo = array_keys($foo, $bar);
        return $this->Foo[0] . '-' . $this->Foo[count($this->Foo) -1)];
    }
}

echo new GetFor(
    [0,1,2,3,4,6,3,1,5], 2
);
下面是一个面向对象的解决方案:

class GetFor
{
    private $Foo[];
    public function __construct(
        array $foo, $bar
    ) {
        $this->Foo = array_keys($foo, $bar);
        return $this->Foo[0] . '-' . $this->Foo[count($this->Foo) -1)];
    }
}

echo new GetFor(
    [0,1,2,3,4,6,3,1,5], 2
);

你在做什么?你期待代码还是你做了什么?看看你在做什么?你期待代码还是你做了什么?看看