0

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"}
  ]
}
2
  • Have you tried the json_decode($arr) ?? Commented Nov 22, 2018 at 7:35
  • @VickyGill Actually am posting data via PHP curl whereby I json_encode the data Commented Nov 22, 2018 at 7:40

2 Answers 2

1

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"
        }
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

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.