문제

수치 적으로 액세스해야 할 연관 배열이 있습니다 (예 : 5 번째 키 값을 얻습니다).

$data = array(
    'one' => 'something', 
    'two' => 'else', 
    'three' => 'completely'
) ;

할 수 있어야합니다.

$data['one']

그리고

$data[0]

같은 가치를 얻으려면 '무언가'.

나의 초기 생각은 키가 숫자인지, 그에 따라 array_values를 사용하여 arrayAccess를 OfrrayAccess를 구현하는 클래스 래퍼를 만드는 것입니다.

class MixedArray implements ArrayAccess {

    protected $_array = array();

    public function __construct($data) {
        $this->_array = $data;
    }

    public function offsetExists($offset) {
        return isset($this->_array[$offset]);
    }

    public function offsetGet($offset) {
        if (is_numeric($offset) || !isset($this->_array[$offset])) {
            $values = array_values($this->_array) ;
            if (!isset($values[$offset])) {
                return false ;
            }
            return $values[$offset] ;
        }                
        return $this->_array[$offset];
    }

    public function offsetSet($offset, $value) {
        return $this->_array[$offset] = $value;
    }

    public function offsetUnset($offset) {
        unset($this->_array[$offset]);
    }    

}

PHP에이를 위해 내장 된 방법이 없는지 궁금합니다. 나는 오히려 기본 기능을 많이 사용하고 있지만 지금까지 나는 이것을하는 것을 보지 못했습니다.

어떤 아이디어?

감사,
Fanis

도움이 되었습니까?

해결책

나는 당신이 그것이 Readonly 데이터베이스 결과 세트라고 언급 한 것을 보았습니다.

MySQL을 사용하고 있다면 이와 같은 일을 할 수 있습니다.

$result = mysql_query($sql);
$data = mysql_fetch_array($result);

mysql_fetch_array 연관 키와 숫자 키가 모두있는 배열을 반환합니다

http://nz.php.net/manual/en/function.mysql-petch-array.php

다른 팁

how about this 

$data = array(
    'one' => 'something', 
    'two' => 'else', 
    'three' => 'completely'
) ;

then 
$keys = array_keys($data);

Then 
$key = $keys[$index_you_want];

Then 
echo $data[$key];

이를위한 내장 방법은 없습니다.

일회성이라면 다음과 같은 것을 사용할 수 있습니다.

$array = array_merge($array, array_values($array));

그래도 배열에 새 항목을 추가하면 업데이트되지 않습니다.

때로는 연관 키나 색인이 있는지 확인하는 것이 더 쉽습니다. is_int()

if(is_int($key))
    return current(array_slice($data, $key, 1));
else
    return $data[$key];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top