0

I have an array as,

either
eight
einstein
eighth

When I convert it to json using json_encode I get the below output,

["either","eight","einstein","eighth"]

But I would like to have a structure like below

[
    {"name":"either"},
    {"name":"eight"},
    {"name":"einstein"},
    {"name":"eighth"}
]

How to get such a json? is there any function in php to achieve this functionality?

2 Answers 2

4

You just massage the array a little with array_map before converting it. You want to go from this structure (in PHP terms):

[
    "either",
    "eight",
    "einstein",
    "eighth"
]

to this:

[
    ["name" => "either"],
    ["name" => "eight"],
    ["name" => "einstein"],
    ["name" => "eighth"],
]

Once you know what must be done, doing it is easy:

$arr = ["either","eight","einstein","eighth"];
$arr = array_map(function($v) { return ['name' => $v]; }, $arr);
echo json_encode($arr);
Sign up to request clarification or add additional context in comments.

Comments

0

You can't redefine array keys like that, it would be an object in JavaScript by the way, but you can have a name array with those children:

<?php

$array = array(
    "name" => array(
        "either",
        "eight",
        "einstein",
        "eighth"
    )
);

Echo json_encode($array);

?>

Demo: https://eval.in/68295

Or, each line could be its own array with name keys.

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.