Home > Software design >  Array format adding extra layer using '=>'
Array format adding extra layer using '=>'

Time:10-07

I'm struggling to find a way to convert my object to the correct format.

I want to replace a function that we currently use on generating detailed array, as you can see below everything is static.

  private function departmentArray($content=[])
    {
            return [ static::$A_DEPT_ID => $content
                   , static::$O_DEPT_ID => $content
                   ];
    }

A sample result when that runs is this

{"3":{"complete":0,"incomplete":0},"5":{"complete":0,"incomplete":0}}

I converted the method

       private function departmentArray($content=[])
    {
        $depts = d::getAllMainDepartment();
  
        $dept_array = [];
        foreach ($depts as $dept) {
            $dept_array[] = array($dept->id => $content);
        }
        
        return $dept_array;
    }

The resulting format looks like this

[{"3":{"complete":0,"incomplete":0}},{"5":{"complete":0,"incomplete":0}}]

How can I maintain the same format on the first version of code?

CodePudding user response:

You don't push into an associative array, you use the new key as an index.

$dept_array[$dept->id] = $content;
  •  Tags:  
  • php
  • Related