PHP输出数组具有相同的标识符
I will need to output an array something along the lines of
[
0 => ['text' => 'category'],
1 => ['text' => category']
]
So basicly an array for each category in my database. I need to output them like this because of how they will be exported to another site. (I cannot foreach inside the export)
My current code, is a foreach loop that runs through my categories. If i var_dump my field variable inside the foreach loop i get the result i want, but as mentioned i need to export everything in the format like above out of the foreach loop.
Code:
foreach ($categories as $category) {
$fieldvalue = ['text' => $category->categoryname];
}
What i have tried:
- Putting the array in a string to explode outside the loop-
- Result: Because of the "same identifier" issue i could only export the last result
What i need to be done:
My current code outputs the array as a text string so basicly
$fieldvalue ? "['text' => '$category->categoryname']";
And my output will be
array:4 [
0 => "['text' => value1]"
1 => "['text' => value2]"
2 => "['text' => value3]"
3 => "['text' => value4]"
]
I just need to get the string to be an array.
Try:
foreach ($categories as $category) {
$fieldvalue[] = ['text' => $category->categoryname];
}
You want the result to be an array that contains many arrays (multi-dimensional array). Using $var[] = $something
adds that $something
as an array object.