1

I am trying to create an array bodyBlocks by looping through all of my matrix fields called blockTextContent:

$bodyBlocks = [];
foreach ($entry->getFieldValue('pageBuilder')->all() as $block){
    switch ($block->type->handle) {
        case 'blockText':               
            $bodyBlocks[] = $block->blockTextContent;
            break;
        }
    }

// Begin defining the response data for this entry
$data = [
    'title' => $entry->title,
    'slug' => $entry->url,
    'status' => $entry->status,
    'textArea' => $bodyBlocks
];  

The JSON response is as below, focusing on the textArea line.

"title": "Title Here",
"slug": "slug-here",
"status": "live",
"textArea": [
    "<p>Text from first 1st block</p>",
    "<p>Text from first 2nd block</p>",
    "<p>Text from first 3rd block</p>",
],
"heroBanner": "img.jpg",

The above is working as expected, cool. BUT I'd like the response to appear as below. Merging that matrix field in to one line in textArea, so without the separating quotation marks and surrounding square brackets [ ]?

My desired response would look like this in the end:

"title": "Title Here",
"slug": "slug-here",
"status": "live",
"textArea": "<p>Text from first 1st block</p> <p>Text from first 2nd block</p> <p>Text from first 3rd block</p>",
"heroBanner": "img.jpg",

Thanks!

1

You would need to join the array into a string, like so:

// Begin defining the response data for this entry
$data = [
    'title' => $entry->title,
    'slug' => $entry->url,
    'status' => $entry->status,
    'textArea' => implode(' ',$bodyBlocks)
]; 
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.