r/PHPhelp • • Aug 23 '20

How to loop this JSON object from php?

From my blade controller, i get this

$data = PageResult::make($result->answers);

return $data;

{"data":[             
            {                
                 "section":"Technology",                 
                 "weighting":"0.15",                          
                    "questions":[                                
                                  {
                                     "id":"1",
                                    "weighting":"0.25",            
                                    "score":"5"    
                                    }, 
                                   {
                                     "id":"2",
                                    "weighting":"0.25",            
                                    "score":"5"    
                                    }
                       ]
                },
                {                
                 "section":"Data",                 
                 "weighting":"0.15",                          
                    "questions":[                                
                                  {
                                     "id":"1",
                                    "weighting":"0.25",            
                                    "score":"5"    
                                    }, 
                                   {
                                     "id":"2",
                                    "weighting":"0.25",            
                                    "score":"5"    
                                    }
                       ]
                }
}

I want to loop through the jSON object, to get the weighting of each question, of each section i have tried something like this..

foreach ($data as $array) {        
    $sections = $array['section'];           
        foreach ($questions as $question) {                        
            $question = $section['questions']                 
         } 
}  

return view('save-results', ['weighting' => $weighting]); 

any ideas?

7 Upvotes

11 comments sorted by

5

u/[deleted] Aug 23 '20

First of all, you have an error in your JSON data. Here is the fixed one:

{
"data": [ { "section": "Technology", "weighting": "0.15", "questions": [ { "id": "1", "weighting": "0.25", "score": "5" }, { "id": "2", "weighting": "0.25", "score": "5" } ] }, { "section": "Data", "weighting": "0.15", "questions": [ { "id": "1", "weighting": "0.25", "score": "5" }, { "id": "2", "weighting": "0.25", "score": "5" } ] } ] }

I, then, created a file 'data.json' and 'test.php'. Here is 'test.php':

<?php
$data = file_get_contents(DIR . '/data.json'); 
$dataArray = json_decode($data, true)['data']; //true because associative, default false 
foreach($dataArray as $sectionData){ 
    $sectionQuestions = $sectionData['questions'];                         
foreach($sectionQuestions as $question){ 
    $questionWeight = $question['weighting']; 
    echo $questionWeight . '<br>'; 
    } 
}

It prints:

0.25
0.25
0.25
0.25

As you see, you made two mistakes: Your JSON data was corrupted and you were looping the whole array, but you have to loop array['data'].

Hope it helps.

P.S.: Get better in debugging PHP with print_r and echoes. Really helps.

1

u/lawyeruphitthegym Aug 23 '20
<?php
$data = json_decode($json, TRUE);
foreach ($data['data'] as $section) {
  foreach ($section['questions'] as $question) {
    printf('weighting for %s (id#%d) is %.2f%s',
      $section['section'],
      $question['id'],
      $question['weighting'],
      PHP_EOL
    );
  }
}

1

u/_username7777 Aug 23 '20

same error :(

json_decode() expects parameter 1 to be string, object given

1

u/lawyeruphitthegym Aug 23 '20

So you're not working with raw JSON. What does print_r($data); look like?

1

u/_username7777 Aug 23 '20

print_r($data);

if i run

$json = PageResult::make($result->answers);

print_r($json);

i get

App\Http\Resources\PageResult Object ( [resource] => a:61:{s:6:"_token";s:40:"xxxxx";s:18:"section_Technology";s:4:"0.15";s:10:"question_1";s:4:"0.25";s:8:"option_1";s:1:"4";s:10:"question_2";s:4:"0.25";s:8:"option_2";s:1:"5";s:10:"question_3";s:4:"0.25";s:8:"option_3";s:1:"5";s:10:"question_4";s:4:"0.25";s:8:"option_4";s:1:"5";s:23:"section_Data_activities";s:4:"0.25";s:10:"question_5";s:4:"0.15";s:8:"option_5";s:1:"5";s:10:"question_6";s:4:"0.15";s:8:"option_6";s:1:"5";s:10:"question_7";s:4:"0.15";s:8:"option_7";s:1:"4";s:10:"question_8";s:4:"0.05";s:8:"option_8";s:1:"5";s:10:"question_9";s:4:"0.10";s:8:"option_9";s:1:"5";s:11:"question_10";s:4:"0.10";s:9:"option_10";s:1:"5";s:11:"question_11";s:4:"0.10";s:9:"option_11";s:1:"5";s:11:"question_12";s:4:"0.10";s:9:"option_12";s:1:"5"} [with] => Array ( ) [additional] => Array ( ) )

if i run

$json = PageResult::make($result->answers);

return $json;

i get

{"data":[{"section":"Technology","weighting":"0.15","questions":[{"id":"1","weighting":"0.25","score":"4","combinedScore":1},{"id":"2","weighting":"0.25","score":"5","combinedScore":1.25},{"id":"3","weighting":"0.25","score":"5","combinedScore":1.25},{"id":"4","weighting":"0.25","score":"5","combinedScore":1.25}]},{"section":"Data activities","weighting":"0.25","questions":[{"id":"5","weighting":"0.15","score":"5","combinedScore":0.75},{"id":"6","weighting":"0.15","score":"5","combinedScore":0.75},{"id":"7","weighting":"0.15","score":"4","combinedScore":0.6},{"id":"8","weighting":"0.05","score":"5","combinedScore":0.25},{"id":"9","weighting":"0.10","score":"5","combinedScore":0.5},{"id":"10","weighting":"0.10","score":"5","combinedScore":0.5},{"id":"11","weighting":"0.10","score":"5","combinedScore":0.5},{"id":"12","weighting":"0.10","score":"5","combinedScore":0.5}]}}]}

1

u/lawyeruphitthegym Aug 23 '20

In that case, try with my code above, but change the first line to:

$data = json_decode((string)$json, TRUE);

1

u/_username7777 Aug 23 '20

$data = json_decode((string)$json, TRUE);

Object of class App\Http\Resources\PageResult could not be converted to string

Sorry about the long copy and paste.. but the below was written by the back end developer, and i'm not super familiar with it!

Resources/pageresult.php

class PageResult extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return $this->formatData($request->all());
    }

    /**
     * @param $data
     * @return array
     */
    public function formatData($data) : array
    {

        $toReturn = [];

        $sectionId = -1;
        foreach($data as $key => $value)
        {
            if ($this->isSection($key)) {
                $sectionId++;
                $section = $this->extractKey($key, 'section');
                $toReturn[$sectionId] = [
                    'section' => str_replace('_', ' ', $section),
                    'weighting' => $value,
                    'questions' => [],
                ];

            }elseif($this->isQuestion($key)) {
                $questionId = $this->extractKey($key, 'question');
                $toReturn[$sectionId]['questions'][] = [
                    'id' => $questionId,
                    'weighting' => $value,
                    'score' => $data['option_' . $questionId],
                    'combinedScore' => $value * $data['option_' . $questionId]
                ];

            }
        }

        return $toReturn;
    }

    /**
     * @param $string
     * @param string $type
     * @return string|string[]
     */
    public function extractKey($string, $type = 'section'): string
    {
        return str_replace($type.'_', '', $string);
    }

    /**
     * @param $label
     * @return bool
     */
    public function isSection($label): bool
    {
        return strpos($label, 'section_') !== false;
    }

    /**
     * @param $label
     * @return bool
     */
    public function isQuestion($label): bool
    {
        return strpos($label, 'question_') !== false;
    }


    /**
     * @param string $label
     * @return bool
     */
    public function isObject(string $label)
    {
        return strpos($label, 'question_') !== false;
    }

}

1

u/lawyeruphitthegym Aug 23 '20

It looks like this instance (PageResult - locally known as $data) has a public method named toArray, which takes an an argument of an \Illuminate\Http\Request instance, and will return an array. If you can pass it this Request object as an argument, you'll likely have everything that you need to work with without parsing JSON.

print_r($data->formatData([Request obj here]));

Alternatively, if you want to go the JSON route, looks like you might be able to access the data with print_r(unserialize($data->resource)), but I'm not sure if this resource property is public… There is also a potential security vulnerability here if you are working with untrusted data.

1

u/Wiikend Aug 23 '20 edited Aug 23 '20

json_decode() won't work because $data is not a JSON string - it's already a PHP data structure. I also think part of your problem is confusing arrays and objects in the data structure you provided; the only thing here that is an array is $data itself ($data is an array of objects) and the questions property of each of these objects. The rest, you have to access using object syntax ($object->property).

This should work:

foreach ($data as $datum) {
    // $datum is the array items in $data, we want the questions property of each array item
    foreach ($datum->questions as $question) {
        // $question is the array items in $datum->questions, which is what we want
        // access weight by doing $question->weighting
        // echo it, put it in an array or do whatever you need to do
    }
}

Let me know if this wasn't quite what you were looking for.

1

u/[deleted] Aug 23 '20

[removed] — view removed comment

1

u/_username7777 Aug 23 '20

Well the above is a JSON object that is printed out from the controller, I'm trying to access this data in the view

$data = PageResult::make($result->answers);
return $data;

If for example, i wanted to save each weighting as a variable so i can print it out in the html of my view or use it in some javascript functions how would i do so? i'm super confused on how to access this data from the controller to the view

I've tried using decode

$data = PageResult::make($result->answers);
$decoded = json_decode($data); 
return $decoded['data'];

but this throws the error: json_decode() expects parameter 1 to be string, object given

as i want to eventually loop through each section, and and get every questions weighting score