dongmou9260 2016-03-23 11:11
浏览 15
已采纳

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.

  • 写回答

1条回答 默认 最新

  • douzhanrun0497 2016-03-23 11:13
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?