php переименовать ключ массива

В PHP, как изменить ключ элемента массива?

У меня есть ассоциативный массив в виде key => value где key-числовое значение, однако это не последовательное числовое значение. Ключ на самом деле является ID-номером, а значение-count. Это нормально для большинства случаев, однако мне нужна функция, которая получает читаемое человеком имя массива и использует его для ключа, не изменяя значение.

Я не видел функции, которая делает это, но я предполагаю, что мне нужно предоставить старый ключ и новый ключ (оба из которых я есть) и преобразовать массив. Есть ли эффективный способ сделать это?

18 ответов

способ сделать это и сохранить порядок массива-это поместить ключи массива в отдельный массив, найти и заменить ключ в этом массиве, а затем объединить его со значениями.

вот функция, которая делает именно это:

если array построен из запроса базы данных, вы можете изменить ключ непосредственно из mysql о себе:

использовать что-то вроде:

ответ от KernelM хорош, но во избежание проблемы, поднятой Грегом в комментарии (конфликтующие ключи), использование нового массива было бы безопаснее

вы можете использовать второй ассоциативный массив, который сопоставляет читаемые человеком имена с идентификаторами. Это также обеспечит отношения от многих до 1. Тогда сделайте что-нибудь вроде этого:

Если вы также хотите, чтобы позиция нового ключа массива была такой же, как и старая, вы можете сделать это:

Если Ваш массив рекурсивен, вы можете использовать эту функцию: проверьте эти данные:

мне нравится решение KernelM, но мне нужно было что-то, что будет обрабатывать потенциальные конфликты ключей (где новый ключ может соответствовать существующему ключу). Вот что я придумал:

затем вы можете выполнить цикл через массив следующим образом:

вот вспомогательная функция для достижения этого:

вернет правда при успешном переименовании, в противном случае false.

эта функция будет сохранить исходный порядок, но может быть проблематичным для очень больших (например, выше записей 10k) массивов относительно производительность и память.

эта альтернативная функция будет делать то же самое, с гораздо лучшую производительность & памяти использование, за счет потери исходного заказа (что не должно быть проблемой, так как это hashtable!)

Источник

array_replace

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

array_replace — Заменяет элементы массива элементами других переданных массивов

Описание

array_replace() не рекурсивная: значения первого массива будут заменены вне зависимости от типа значений второго массива, даже если это будут вложенные массивы.

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

Массив, элементы которого требуется заменить.

Массивы, из которых будут браться элементы для замены. Значения следующего массива затирают значения предыдущего.

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

Возвращает массив ( array ) или null в случае возникновения ошибки.

Примеры

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

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

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

User Contributed Notes 14 notes

// we wanted the output of only selected array_keys from a big array from a csv-table
// with different order of keys, with optional suppressing of empty or unused values

Here is a simple array_replace_keys function:

print_r(array_replace_keys([‘one’=>’apple’, ‘two’=>’orange’], [‘one’=>’ett’, ‘two’=>’tvo’]);
// Output
array(
‘ett’=>’apple’,
‘tvo’=>’orange’
)

Simple function to replace array keys. Note you have to manually select wether existing keys will be overrided.

To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:

array(3) <
«id» => NULL
«login» => string(8) «john.doe»
«credit» => int(100)
>

I would like to add to my previous note about my polecat_array_replace function that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

$array1 = array( «berries» => array( «strawberry» => array( «color» => «red», «food» => «desserts»), «dewberry» = array( «color» => «dark violet», «food» => «pies»), );

$array2 = array( «food» => «wine»);

This is will replace the value for «food» for «dewberry» with «wine».

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I’ve gained from this site.

I got hit with a noob mistake. 🙂

When the function was called more than once, it threw a function redeclare error of course. The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision. A simple logical step was all that was needed.

With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own. Since this site has helped me so much, I felt the need to return the favor. 🙂

$array2 = array( «food» => «wine» );

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I’ve gained from this site.

In some cases you might have a structured array from the database and one
of its nodes goes like this;

# string to transform
$string = «

name: %s, json: %s, title: %s

?>

I hope that this will save someone’s time.

Источник

Как переименовать ключи массива в PHP?

Я хотел бы переименовать все ключи массива с именем «url» в «value». Что было бы хорошим способом сделать это?

8 ответов

Мне нужно переименовать ключи динамического массива и создать новый массив. Вот массив как задано: array(21) < [0161] =>array(5) < [L_NAME0161] =>string(13) john%20Hewett [L_TRANSACTIONID0161] => string(17) 50350073XN1446019 [L_AMT0161] => string(6) 8%2e50 [L_FEEAMT0161] =>.

Выполните цикл, установите новый ключ, снимите старый ключ.

Говоря о функциональном PHP, у меня есть более общий ответ:

Рекурсивная функция php переименования ключей:

Это должно работать в большинстве версий PHP 4+. Карта массива с использованием анонимных функций не поддерживается ниже 5.3.

Кроме того, примеры foreach выдадут предупреждение при использовании строгой обработки ошибок PHP.

Вот небольшая многомерная функция переименования ключей. Он также может использоваться для обработки массивов, чтобы иметь правильные ключи для целостности всего приложения. Он не будет выдавать никаких ошибок, если ключ не существует.

Использование простое. Вы можете либо изменить один ключ, как в вашем примере:

или более сложный многоключевой

Используйте это все время, надеюсь, это поможет!

Я загружаю файл на сервер в PHP. Теперь я хочу переименовать файл в новое имя, но не могу этого сделать. Предлагаемое новое имя файла будет состоять из значения из одного ассоциативного массива и имени переменной. Для достижения этой цели я сделал следующий код, но не смог получить новый.

У меня есть такой массив, ключи-это временные метки эпохи, они использовались для упорядочения файлов по дате, теперь я хочу переименовать ключи в 0, 1, 2, 3 и т. д. Array($files) ( [1365168386] => _MG_5704.jpg [1368201277] => _MG_5702.jpg [1368201719] => jetty.jpg [1368202375] =>.

Это из дублированного вопроса

Похожие вопросы:

Я не уверен, что это правильные слова, чтобы выразить мой вопрос. У меня есть следующий массив, результат этапа фильтрации. Как вы можете видеть, ключи не являются последовательными [например.

Мне нужно переименовать ключи динамического массива и создать новый массив. Вот массив как задано: array(21) < [0161] =>array(5) < [L_NAME0161] =>string(13) john%20Hewett.

У меня есть ассоциативный массив в php. Когда я делаю на нем кубик, то получаю правильные значения следующим образом: array(1) < [0]=>array(1) < [123]=>string(5) Hello >> Но когда я пытаюсь.

Я загружаю файл на сервер в PHP. Теперь я хочу переименовать файл в новое имя, но не могу этого сделать. Предлагаемое новое имя файла будет состоять из значения из одного ассоциативного массива и.

У меня есть такой массив, ключи-это временные метки эпохи, они использовались для упорядочения файлов по дате, теперь я хочу переименовать ключи в 0, 1, 2, 3 и т. д. Array($files) ( [1365168386].

У меня есть массив массивов, что-то вроде этого: Array ( [0] => Array ( [0] => DC1F180E-FE57-622C-28AE-8194843B4D84 [1] => First Choice [2] => 1 ) [1] => Array ( [0] =>.

Источник

array_keys

(PHP 4, PHP 5, PHP 7, PHP 8)

array_keys — Возвращает все или некоторое подмножество ключей массива

Описание

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

Массив, содержащий возвращаемые ключи.

Если указано, будут возвращены только ключи у которых значения элементов массива совпадают с этим параметром.

Определяет использование строгой проверки на равенство (===) при поиске.

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

Примеры

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

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

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

User Contributed Notes 28 notes

It’s worth noting that if you have keys that are long integer, such as ‘329462291595’, they will be considered as such on a 64bits system, but will be of type string on a 32 bits system.

?>

will return on a 64 bits system:

but on a 32 bits system:

I hope it will save someone the huge headache I had 🙂

Here’s how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:

Since 5.4 STRICT standards dictate that you cannot wrap array_keys in a function like array_shift that attempts to reference the array.

Invalid:
echo array_shift( array_keys( array(‘a’ => ‘apple’) ) );

But Wait! Since PHP (currently) allows you to break a reference by wrapping a variable in parentheses, you can currently use:

echo array_shift( ( array_keys( array(‘a’ => ‘apple’) ) ) );

However I would expect in time the PHP team will modify the rules of parentheses.

There’s a lot of multidimensional array_keys function out there, but each of them only merges all the keys in one flat array.

Here’s a way to find all the keys from a multidimensional array while keeping the array structure. An optional MAXIMUM DEPTH parameter can be set for testing purpose in case of very large arrays.

NOTE: If the sub element isn’t an array, it will be ignore.

output:
array(
‘Player’ => array(),
‘LevelSimulation’ => array(
‘Level’ => array(
‘City’ => array()
)
),
‘User’ => array()
)

array (size=4)
0 => string ‘e’ (length=1)
1 => int 1
2 => int 2
3 => int 0

—-
expected to see:
dude dude dude

Sorry for my english.

I wrote a function to get keys of arrays recursivelly.

Here’s a function I needed to collapse an array, in my case from a database query. It takes an array that contains key-value pairs and returns an array where they are actually the key and value.

?>

Example usage (pseudo-database code):

= db_query ( ‘SELECT name, value FROM properties’ );

/* This will return an array like so:

/* Now this array looks like:

?>

I found this handy for using with json_encode and am using it for my project http://squidby.com

This function will print all the keys of a multidimensional array in html tables.
It will help to debug when you don?t have control of depths.

An alternative to RQuadling at GMail dot com’s array_remove() function:

The position of an element.

One can apply array_keys twice to get the position of an element from its key. (This is the reverse of the function by cristianDOTzuddas.) E.g., the following may output «yes, we have bananas at position 0».

Hope this helps someone.

# array_keys() also return the key if it’s boolean but the boolean will return as 1 or 0. It will return empty if get NULL value as key. Consider the following array:

Array
(
[ 0 ] => first_index
[ 1 ] => 1
[ 2 ] => 0
[ 3 ] => 4
[ 4 ] => 08
[ 5 ] => 8
[ 6 ] =>
)

This function will extract keys from a multidimensional array

Array
(
[color] => Array
(
[1stcolor] => blue
[2ndcolor] => red
[3rdcolor] => green
)

[size] => Array
(
[0] => small
[1] => medium
[2] => large
)

Array
(
[0] => color
[1] => 1stcolor
[2] => 2ndcolor
[3] => 3rdcolor
[4] => size
[5] => 0
[6] => 1
[7] => 2
)

All the cool notes are gone from the site.

Here’s an example of how to get all the variables passed to your program using the method on this page. This prints them out so you can see what you are doing.

Simple ways to prefixing arrays;

[1] => Array
(
[product_id] => 2
[product_name] => Bar
)

I was looking for a function that deletes either integer keys or string keys (needed for my caching).
As I didn’t find a function I came up with my own solution.
I didn’t find the propiest function to post to so I will post it here, hope you find it useful.

?>

You can of course define constants to have a nicer look, I have chosen these: EXTR_INT = 1; EXTR_STRING = 2
EXTR_INT will return an array where keys are only integer while
EXTR_STRING will return an array where keys are only string

A needed a function to find the keys which contain part of a string, not equalling a string.

Источник

array_flip

(PHP 4, PHP 5, PHP 7, PHP 8)

array_flip — Меняет местами ключи с их значениями в массиве

Описание

Функция array_flip() возвращает массив ( array ) наоборот, то есть ключи массива array становятся значениями, а значения массива array становятся ключами.

Если значение встречается несколько раз, для обработки будет использоваться последний встреченный ключ, а все остальные будут потеряны.

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

Массив переворачиваемых пар ключ/значение.

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

Возвращает перевёрнутый массив в случае успешного выполнения и null в случае возникновения ошибки.

Примеры

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

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

Пример #2 Пример использования array_flip() с коллизиями

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

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

User Contributed Notes 18 notes

This function is useful when parsing a CSV file with a heading column, but the columns might vary in order or presence:

?>

I find this better than referencing the numerical array index.

array_flip will remove duplicate values in the original array when you flip either an associative or numeric array. As you might expect it’s the earlier of two duplicates that is lost:

array(3) <
[0] => string(3) «one»
[1] => string(3) «two»
[2] => string(3) «one»
>

This may be good or bad, depending on what you want, but no error is thrown.

array_flip() does not retain the data type of values, when converting them into keys. 🙁

It is valid expectation that string values «1», «2» and «3» would become string keys «1», «2» and «3».

When you do array_flip, it takes the last key accurence for each value, but be aware that keys order in flipped array will be in the order, values were first seen in original array. For example, array:

In my application I needed to find five most recently commented entries. I had a sorted comment-id => entry-id array, and what popped in my mind is just do array_flip($array), and I thought I now would have last five entries in the array as most recently commented entry => comment pairs. In fact it wasn’t (see above, as it is the order of values used). To achieve what I need I came up with the following (in case someone will need to do something like that):

First, we need a way to flip an array, taking the first encountered key for each of values in array. You can do it with:

Well, and to achieve that «last comments» effect, just do:

$array = array_reverse($array, true);
$array = array_flip(array_unique($array));
$array = array_reverse($array, true);

In the example from the very beginning array will become:

Just what I (and maybe you?) need. =^_^=

In case anyone is wondering how array_flip() treats empty arrays:

( array_flip (array()));
?>

results in:

I wanted to know if it would return false and/or even chuck out an error if there were no key-value pairs to flip, despite being non-intuitive if that were the case. But (of course) everything works as expected. Just a head’s up for the paranoid.

I needed a way to flip a multidimensional array and came up with this function to accomplish the task. I hope it helps someone else.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *