php - Assign a key to all array values and change each key/pair into a separate array within the array
Get the solution ↓↓↓Here is my input:
$testKeys = ['test1', 'test2', 'test3', 'test4', 'test5'];
I want to change this into:
[['Name' => 'test1'], ['Name' => 'test2'], ['Name' => 'test3'], ...]
I have tried doing$testKeys = array_fill_keys($testKeys, 'Name');
But this does not put them into separate arrays and it makes the key/value the opposite of what I want.
Can anyone help me please? The key is always gonna be 'Name', it will always be a single key/value pair in each separate array inside an array. Thanks.
Answer
Solution:
After following suggestions, I found out I can do it like this:
foreach ($testKeys as $key => &$value) {
$value = ['Name' => $value];
unset($value);
}
// Output: [['Name' => 'test1'], ['Name' => 'test2'], ...]
Thank you.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: illegal string offset
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.