Patweb
Patweb

Reputation: 133

Issue posting a PHP array to an API requiring an array of JSON objects

Am working on some PHP inputs which I store in an array, then I post to an API requiring an array of JSON objects. I keep getting errors when posting the data below..

Please assist?

Array am trying to post

$children = ["child_name" => $cName , "child_dob" => $cDob]; 
dd($children);

Output in browser after die dump

array:2 [
  "child_name" => array:5 [
    0 => "Child 1"
    1 => "mnmnmn"
    2 => "mnmnmnm"
    3 => "nbnbnb"
    4 => "nbjhjgkgjhkg"
  ]
  "child_dob" => array:5 [
    0 => "2018-11-01"
    1 => "2018-11-02"
    2 => "2018-11-09"
    3 => "2018-11-14"
    4 => "2018-11-08"
  ]
]

Sample data from API I need to POST to

{
"children":[
    {"child_name":"abc","child_dob":"23-05-2015"}
  ]
}

Upvotes: 0

Views: 39

Answers (2)

karthzDIGI
karthzDIGI

Reputation: 403

Nigel Ren has already answered the question.

But for those who want to write a solution in a more functional programming style of coding in PHP. I am attempting to solve it, by being declarative than imperative.

<?php
$cName = array('Child 1', 'Child 2', 'Child 3');    
$cDob = array('2018-11-01', '2018-11-02', '2018-11-03');

function mapChildNameToDob($childName,  $dob)
{
    return array(
        'child_name' => $childName, 
        'child_dob' => $dob
    );
}

$children['children'] = array_map("mapChildNameToDob", $cName, $cDob );     
echo json_encode($children);

Or if you want to use anonymous callback function, you can write it like this:

<?php
$cName = array('Child 1', 'Child 2', 'Child 3');
$cDob = array('2018-11-01', '2018-11-02', '2018-11-03');

$children['children'] = array_map(function($childName,  $dob) {
    return array(
        'child_name' => $childName, 
        'child_dob' => $dob
    ); 
}, $cName, $cDob ); 

echo json_encode($children);

Upvotes: 0

Nigel Ren
Nigel Ren

Reputation: 57131

The problem is that you have an array of names and DOB's, it is quite easy using a foreach() to create the output your after by looping over the names and adding in the corresponding DOB...

$cName = ["Child 1", "cchild 2"];
$cDob = ["2018-01-01", "2018-02-02"];

$children = [];
foreach ( $cName as $key => $name ) {
    $children[] = ["child_name" => $name , "child_dob" => $cDob[$key]];
}

echo json_encode([ "children" => $children], JSON_PRETTY_PRINT););

Results in...

{
    "children": [
        {
            "child_name": "Child 1",
            "child_dob": "2018-01-01"
        },
        {
            "child_name": "cchild 2",
            "child_dob": "2018-02-02"
        }
    ]
}

Upvotes: 1

Related Questions