0

The issue at hand is that I have an array within my JSON after I decoded it.

I collect a few items from the database, and place them in an array in an foreach.

Data to place in array:

    [ 0 =>
        [ 0 => [
            'title' => 'Title 1',
            'files' => [
                'name' => 'file_name',
                'url' => 'file_url'
            ]
        ]
        ],
        [ 1 => [
            'title' => 'Title 1',
            'files' => [
                'name' => 'file_name',
                'url' => 'file_url'
            ]
        ]
        ],
        [ 2 => [
            'title' => 'Title 3',
            'files' => [
                'name' => 'file_name',
                'url' => 'file_url'
            ]
        ]
        ],
        [ 3 => [
            'title' => 'Title 4',
            'files' => [
                'name' => 'file_name',
                'url' => 'file_url'
            ]
        ]
        ]
    ]

Next I'll place it in an array to place all files belonging to the same title :

    $dataArray = [];
    foreach ($array as $key => $value) {
        $dataArray['dataInfo'][] = [
            'title' => $value['title'],
            'files' => [
                'name' => $value['files']['name'],
                'url' => $value['files']['url']
            ]
        ];
    }

Then I'll convert it to an JSON with:

json_encode(dataArray);

The result is:

    {
      "dataInfo": [
        {
            "title": "Title 1",
          "files": {
            "name": "file name",
            "url": "file_url"
          }
        },
        {
            "title": "Title 1",
          "files": {
            "name": "file name",
            "url": "file_url"
          }
        },
        {
            "title": "Title 3",
          "files": {
            "name": "file name",
            "url": "file_url"
          }
        },
        {
            "title": "Title 4",
          "files": {
            "name": "file name",
            "url": "file_url"
          }
        }
      ]
    }

What I want is:

    {
        "dataInfo": [
        {
            "title": "Title 1",
          "files": {
            "name": "file name",
            "url": "file_url",
          }, 
          {
            "name": "file name",
            "url": "file_url",
          }
        },
        {
            "title": "Title 3",
          "files": {
            "name": "file name",
            "url": "file_url"
          }
        },
        {
            "title": "Title 4",
          "files": {
            "name": "file name",
            "url": "file_url"
          }
        }
      ]
    }

How can I make this happen?

1
  • You can't add dangling commas and still have it be valid JSON, JSON does not support this. Commented Jul 10, 2018 at 13:07

2 Answers 2

1

This should work I guess:

$dataArray = [];
$previousTitle = '';
foreach ($array as $key => $value) {
    if ($previousTitle === $value['title']) {
        $dataArray['dataInfo'][$previousTitle]['files'] += [
            'name' => $value['files']['name'],
            'url' => $value['files']['url']
        ]
    } else {
        $dataArray['dataInfo'][] = [
            'title' => $value['title'],
            'files' => [
                'name' => $value['files']['name'],
                'url' => $value['files']['url']
            ]
        ];
    }

    $previousTitle = $value['title'];
}
Sign up to request clarification or add additional context in comments.

2 Comments

What if the titles are not in order? Let's say we have title1, title2, title1? Will the $previousTitle work then?
Nope, it won't. You can always switch out the $previousTitle for an array and then do an array search in the if statement if necessary. Good call though!
0

Laravel has the collections that will allow you do do this:

$result = [ "dataInfo" => 
    collect($dataArray["dataInfo"])
        ->groupBy('title')
        ->map(function ($group, $title) {                    
        return [
            "title" => $title,
            "files" => $group->pluck("files")->all()
        ];
    })
];

Breaking this down:

You first transform $dataArray["dataInfo"] by making it a collection then grouping it by "title". Then each group is transformed into an entry with title and an array of the files.

2 Comments

Oh this is sweet, nice call
This one did it for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.