从字符串创建数组 - PHP

我有一个字符串,我需要从中获取关联数组。我可以自由地将字符串修改为看起来像数组,但我仍然无法从中获取数组。我尝试过explode、json等。


 $string = $row->id . ',' . $row->title . ',';

// 1,Home,3,Services,6,Service 1,7,Service 2,2,Products

例子


    public function Menu($parent = null) {

$query = $this->menuManager->getPublicMenus()->where('parent', null)->order('sort_order');

        if ($this->menuManager->getPublicMenus()->count() > 0) {

            $menu = '';

            foreach ($query as $row) {

                $menu .= $row->id . ',' . $row->title . ',';

                $menu .= $this->Menu($row->id);

            }

            return $menu;

        }

    }

我需要输出:


array

1 => "Home"

3 => "Services"

6 => "Service 1"

7 => "Service 2"

2 => "Products"


回首忆惘然
浏览 78回答 1
1回答

喵喔喔

如果您必须使用该字符串。$input = '1,Home,3,Services,6,Service 1,7,Service 2,2,Products';$keysAndValues = explode(',', $input);$result = [];$count = count($keysAndValues);for ($i = 0; $i < $count; $i+=2) {&nbsp; &nbsp; $key = $keysAndValues[$i];&nbsp; &nbsp; $value = $keysAndValues[$i+1];&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; $result[$key] = $value;}工作示例。输出array(5) {&nbsp; &nbsp; [1]=>&nbsp; &nbsp; string(4) "Home"&nbsp; &nbsp; [3]=>&nbsp; &nbsp; string(8) "Services"&nbsp; &nbsp; [6]=>&nbsp; &nbsp; string(9) "Service 1"&nbsp; &nbsp; [7]=>&nbsp; &nbsp; string(9) "Service 2"&nbsp; &nbsp; [2]=>&nbsp; &nbsp; string(8) "Products"}我看到你添加了一个例子。要获取数组,在 Menu 方法中执行此操作要干净得多:$menu = [];foreach ($query as $row) {&nbsp; &nbsp; $menu[$row->id] = [&nbsp; &nbsp; &nbsp; &nbsp; 'title' => $row->title,&nbsp; &nbsp; &nbsp; &nbsp; 'children' => $this->Menu($row->id)&nbsp; &nbsp; ];}return $menu;
打开App,查看更多内容
随时随地看视频慕课网APP