JSON编码firstname + Lastname = fullname

时间:2017-03-13 19:35:47

标签: php arrays json

我想将firstname和lastname合并为fullname

$record[0]["firstname"]="foo";
$record[0]["lastname"]="bar";
$record[0]["age"]="20";

for ($i=0; $i<3; $i++) {

    $foobar_array[] = array(
            'fullname' => [$record[$i]['firstname'], $record[$i]['lastname']],
            'age' => $record[$i]['age']

    );


}

echo json_encode($foobar_array);

我想要显示json字符串

[{"fullname":"foo bar ","age":"20"}]

2 个答案:

答案 0 :(得分:2)

此:

$foobar_array[] = array(
     'fullname' => $record[$i]['firstname'] . ' ' . $record[$i]['lastname'],
      'age' => $record[$i]['age']
);

答案 1 :(得分:1)

$record = [
    [
        'firstname' => 'foo',
        'lastname' => 'bar',
        'age' => 20,
    ]
];

foreach ($record as $r) {
    $foobar_array[] = [
            'fullname' => $r['firstname'].' '.$r['lastname'],
            'age' => $r['age']
    ];
}

echo json_encode($foobar_array);

- &GT;

[{"fullname":"foo bar","age":"20"}]