Свой key массив php

Создание ключей для массива. Использование файла

Прошу обратить внимание на то, что глубина массива не фиксирована, а может быть бесконечной.

Все что я смог сделать —
1. разбить стринг на линии (массив);
2. разбить каждую линию на два куска — слева от «=» — получаю ключи массивов с точками
3. разбить каждое словой точками, и получить все все ключи конечного массива

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
array(6) { [0]=> array(1) { [0]=> string(2) "id" } [1]=> array(2) { [0]=> string(6) "server" [1]=> string(4) "type" } [2]=> array(3) { [0]=> string(6) "server" [1]=> string(4) "host" [2]=> string(2) "ip" } [3]=> array(3) { [0]=> string(6) "server" [1]=> string(4) "host" [2]=> string(8) "provider" } [4]=> array(2) { [0]=> string(5) "image" [1]=> string(4) "name" } [5]=> array(2) { [0]=> string(5) "image" [1]=> string(4) "size" } }

Но как используя эти данные получить ассоциативный массив?

Рассмотрим этот кусок массива

array(3) { [0]=> string(6) "server" [1]=> string(4) "host" [2]=> string(8) "provider" }

У нас есть три значения, три элемента. Как получить такое — $result[‘server’][‘host’][‘provider’]
Насколько мне известно, готовых функций в PHP как таковых нет.

Какое решение предлагаете, коллеги?

Создание ассоциативного массива с динамическими названиями ключей
Задача создать ассоциативный массив из базы Как правильно реализовать названия ячейки из базы.

Динамическое создание SQL не поддерживается для SelectCommand, не возвращающей сведений о столбце ключей
При подключении базы данных в проект возникает ошибка, Динамическое создание SQL для UpdateCommand.

Читайте также:  Read from console javascript

Эксперт PHP

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
$arr = ["server", "host", "provider"]; $value = 'ucom'; $result = []; foreach(array_reverse($arr) as $k => $v) { if($k === 0) $result[$v] = $value; else $result = [$v => $result]; } echo '
'; print_r($result);

Добавлено через 6 минут
Ещё можете глянуть переписку хелпера Laravel для работы с массивами:
https://github.com/rappasoft/l. elpers.php

Обратите внимание на функции get, set, dot. Пример:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
function get($array, $key, $default = null)  if (is_null($key)) return $array; if (isset($array[$key])) return $array[$key]; foreach (explode('.', $key) as $segment) { if ( ! is_array($array)  $array = $array[$segment]; } return $array; } $arr = ['1' => ['2' => ['3' => 'value']]]; echo get($arr, '1.2.3');

Jodah, благодарю. Сегодня попробую

Добавлено через 9 часов 5 минут
Jodah, я попробовал использовать ваш первый код. В вашем примере только один массив ключей, у меня же массив массивов ключей. Решил использовать еще один цикл для этого, но вышло не правильно.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
//File content $string = 'id=www server.type=linux server.host.ip=127.0.0.1 server.host.provider=ucom image.name=test.jpg image.size=1000'; //Final result $result = []; //Keys array $key_ar = []; //Values array $val_ar = []; //Getting keys and values from file (string) foreach (explode("\n", $string) as $line){ array_push($key_ar, explode('.',explode('=', $line)[0])); array_push($val_ar, explode('=', $line)[1]); } //Getting final array with keys and values foreach ($key_ar as $line_number=>$line){ $depth = count($line); foreach(array_reverse($line) as $k => $key_name) { if($k === 0) $result[$key_name] = $val_ar[$line_number]; else $result = [$key_name => $result]; //Проблема судя по всему тут } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
array(1) { ["image"]=> array(2) { ["image"]=> array(2) { ["server"]=> array(1) { ["host"]=> array(2) { ["server"]=> array(1) { ["host"]=> array(2) { ["server"]=> array(2) { ["id"]=> string(3) "www" ["type"]=> string(5) "linux" } ["ip"]=> string(9) "127.0.0.1" } } ["provider"]=> string(4) "ucom" } } ["name"]=> string(8) "test.jpg" } ["size"]=> string(4) "1000" } }

Источник

Свой key массив php

// Before php 5.4
$array = array(1,2,3);

// since php 5.4 , short syntax
$array = [1,2,3];

// I recommend using the short syntax if you have php version >= 5.4

Used to creating arrays like this in Perl?

Looks like we need the range() function in PHP:

$array = array_merge (array( 'All' ), range ( 'A' , 'Z' ));
?>

You don't need to array_merge if it's just one range:

There is another kind of array (php>= 5.3.0) produced by

$array = new SplFixedArray(5);

Standard arrays, as documented here, are marvellously flexible and, due to the underlying hashtable, extremely fast for certain kinds of lookup operation.

Supposing a large string-keyed array

$arr=['string1'=>$data1, 'string2'=>$data2 etc. ]

when getting the keyed data with

php does *not* have to search through the array comparing each key string to the given key ('string1') one by one, which could take a long time with a large array. Instead the hashtable means that php takes the given key string and computes from it the memory location of the keyed data, and then instantly retrieves the data. Marvellous! And so quick. And no need to know anything about hashtables as it's all hidden away.

However, there is a lot of overhead in that. It uses lots of memory, as hashtables tend to (also nearly doubling on a 64bit server), and should be significantly slower for integer keyed arrays than old-fashioned (non-hashtable) integer-keyed arrays. For that see more on SplFixedArray :

Unlike a standard php (hashtabled) array, if you lookup by integer then the integer itself denotes the memory location of the data, no hashtable computation on the integer key needed. This is much quicker. It's also quicker to build the array compared to the complex operations needed for hashtables. And it uses a lot less memory as there is no hashtable data structure. This is really an optimisation decision, but in some cases of large integer keyed arrays it may significantly reduce server memory and increase performance (including the avoiding of expensive memory deallocation of hashtable arrays at the exiting of the script).

When creating arrays , if we have an element with the same value as another element from the same array, we would expect PHP instead of creating new zval container to increase the refcount and point the duplicate symbol to the same zval. This is true except for value type integer.
Example:

$arr = ['bebe' => 'Bob', 'age' => 23, 'too' => 23 ];
xdebug_debug_zval( 'arr' );

(refcount=2, is_ref=0)
array (size=3)
'bebe' => (refcount=1, is_ref=0)string 'Bob' (length=3)
'age' => (refcount=0, is_ref=0)int 23
'too' => (refcount=0, is_ref=0)int 23

but :
$arr = ['bebe' => 'Bob', 'age' => 23, 'too' => '23' ];
xdebug_debug_zval( 'arr' );

(refcount=2, is_ref=0)
array (size=3)
'bebe' => (refcount=1, is_ref=0)string 'Bob' (length=3)
'age' => (refcount=0, is_ref=0)int 23
'too' => (refcount=1, is_ref=0)string '23' (length=2)
or :

$arr = ['bebe' => 'Bob', 'age' => [1,2], 'too' => [1,2] ];
xdebug_debug_zval( 'arr' );

(refcount=2, is_ref=0)
array (size=3)
'bebe' => (refcount=1, is_ref=0)string 'Bob' (length=3)
'age' => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2
'too' => (refcount=2, is_ref=0)
array (size=2)
0 => (refcount=0, is_ref=0)int 1
1 => (refcount=0, is_ref=0)int 2

This function makes (assoc.) array creation much easier:

function arr (. $array )< return $array ; >
?>

It allows for short syntax like:

$arr = arr ( x : 1 , y : 2 , z : 3 );
?>

Instead of:

$arr = [ "x" => 1 , "y" => 2 , "z" => 3 ];
// or
$arr2 = array( "x" => 1 , "y" => 2 , "z" => 3 );
?>

Sadly PHP 8.2 doesn't support this named arguments in the "array" function/language construct.

Источник

Свой key массив php

key — Выбирает ключ из массива

Описание

key() возвращает индекс текущего элемента массива.

Список параметров

Возвращаемые значения

Функция key() просто возвращает ключ того элемента массива, на который в данный момент указывает внутренний указатель массива. Она не сдвигает указатель ни в каком направлении. Если внутренний указатель указывает вне границ массива или массив пуст, key() возвратит null .

Список изменений

Версия Описание
8.1.0 Вызов функции в объекте ( object ) объявлен устаревшим. Либо сначала преобразуйте объект ( object ) в массив ( array ) с помощью функции get_mangled_object_vars() , либо используйте методы, предоставляемые классом, реализующим интерфейс Iterator , например, ArrayIterator .
7.4.0 Экземпляры классов SPL теперь обрабатываются как пустые объекты, не имеющие свойств, вместо вызова метода Iterator с тем же именем, что и эта функция.

Примеры

Пример #1 Пример использования key()

$array = array(
'fruit1' => 'apple' ,
'fruit2' => 'orange' ,
'fruit3' => 'grape' ,
'fruit4' => 'apple' ,
'fruit5' => 'apple' );

// этот цикл выведет все ключи ассоциативного массива,
// значения которых равны "apple"
while ( $fruit_name = current ( $array )) if ( $fruit_name == 'apple' ) echo key ( $array ), "\n" ;
>
next ( $array );
>
?>

Результат выполнения данного примера:

Смотрите также

  • current() - Возвращает текущий элемент массива
  • next() - Перемещает указатель массива вперёд на один элемент
  • array_key_first() - Получает первый ключ массива
  • foreach

User Contributed Notes 5 notes

Note that using key($array) in a foreach loop may have unexpected results.

When requiring the key inside a foreach loop, you should use:
foreach($array as $key => $value)

I was incorrectly using:
foreach( $array as $value )
$mykey = key ( $array );
>
?>

and experiencing errors (the pointer of the array is already moved to the next item, so instead of getting the key for $value, you will get the key to the next value in the array)

CORRECT:
foreach( $array as $key => $value )
$mykey = $key ;
>

A noob error , but felt it might help someone else out there .

Suppose if the array values are in numbers and numbers contains `0` then the loop will be terminated. To overcome this you can user like this

while ( $fruit_name = current ( $array ))

echo key ( $array ). '
' ;
next ( $array );
>

// the way will be break loop when arra('2'=>0) because its value is '0', while(0) will terminate the loop

// correct approach
while ( ( $fruit_name = current ( $array )) !== FALSE )

echo key ( $array ). '
' ;
next ( $array );
>
//this will work properly
?>

Needed to get the index of the max/highest value in an assoc array.
max() only returned the value, no index, so I did this instead.

reset ( $x ); // optional.
arsort ( $x );
$key_of_max = key ( $x ); // returns the index.
?>

(Editor note: Or just use the array_keys function)

Make as simple as possible but not simpler like this one 🙂

In addition to FatBat's response, if you'd like to find out the highest key in an array (assoc or not) but don't want to arsort() it, take a look at this:

$arr = [ '3' => 14 , '1' => 15 , '4' => 92 , '15' => 65 ];

$key_of_max = array_search ( max ( $arr ) , $arr );

  • Функции для работы с массивами
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

Оцените статью