I have the code below. I am trying to loop through an array within a string and return the results to be a sub part of the string.
$household = '{
"data": {
"attributes": {
"name":"'.rgar( $entry, '1.6' ).'"
},
"relationships": {
"people":{
"data":[
'.
foreach ($family_ids[] as $fam_member){
return '{"type":"Person","id":"'.$fam_member.'"}';
}.'
]
},
"primary_contact":{
"data":{"type":"Person","id":"1"}
}
}
}
}';
echo($household);
My expected results would be along the lines of this
'{
"data": {
"attributes": {
"name":"'.rgar( $entry, '1.6' ).'"
},
"relationships": {
"people":{
"data":[
{"type":"Person","id":"2"},
{"type":"Person","id":"3"},
{"type":"Person","id":"4"}, //note the commas
{"type":"Person","id":"5"}
]
},
"primary_contact":{
"data":{"type":"Person","id":"1"}
}
}
}
}';
I believe my issue is related to my quotation marks to break in and out of the string. However I am also not sure how to address to comma being removed for the last result.
You need to assign foreach value to a variable first and then assign this variable to your json.
$data = [];
foreach ($family_ids as $fam_member){
$data[]= ["type"=>"Person","id"=> $fam_member]
}
$household = '{
"data": {
"attributes": {
"name":"'.rgar( $entry, '1.6' ).'"
},
"relationships": {
"people":{
"data":'. json_encode($data) . '
},
"primary_contact":{
"data":{"type":"Person","id":"1"}
}
}
}
}';
echo($household);
A hardcoded sample example Output:- https://3v4l.org/enrGP
You can concatenate $household
variable in such a way like this. Although @AliveToDie's solution is best but this solution will be easy to understand for beginners
$household = '';
$household .= '{
"data": {
"attributes": {
"name":"'.rgar( $entry, '1.6' ).'"
},
"relationships": {
"people":{
"data":[
';
foreach ($family_ids[] as $key => $fam_member){
$household .= '{"type":"Person","id":"'.$fam_member.'"}';
if((count($family_ids)-1)!=$key)// if foreach loop reaches the last element then it won't print the comma
$household .= ',';
}
$household .='
]
},
"primary_contact":{
"data":{"type":"Person","id":"1"}
}
}
}
}';
echo($household);
Is there a reason for building a json string by escaping your quotes?
Perhaps this solution (which I think will give you more freedom, and you don't have to worry about escaping quotes etc) would be beneficial to you:
$household['data']['attributes']['name'] = rgar( $entry, '1.6' );
$household['data']['relationships']['people']['data'] = array(); // In case $family_ids is empty
foreach ($family_ids[] as $fam_member):
$household['data']['relationships']['people']['data'][] = array(
'type' => 'Person',
'id' => $fam_member
);
endforeach;
$household['data']['relationships']['primary_contact']['data'] = array(
'type' => 'Person',
'id' => '1'
);
$json = json_encode($household);
$prettyJson = json_encode($household, JSON_PRETTY_PRINT);
echo $prettyJson;
Then, you can either use $json
for your json, or, if you needed it to be formatted and pretty, you can use $prettyJson
;