0

This is my array format:

$data=["error.png","invoice_1.pdf","invoice2.png"];

But I want to this format:

$data=[{"file":"error.png"},{"file":"invoice_1.pdf"},{"file":"invoice2.png"}]

Thank you.

2
  • why would you want to give the same key to all variables ? Commented Nov 21, 2014 at 10:24
  • 1
    This really is very simple logic. You've made no attempt to do this yourself & evidently not even searched for what you wanted, because you're most definitely not this first to want to do this simple thing. Commented Nov 21, 2014 at 11:14

4 Answers 4

2

You should create a new array.

And loop through your existing array.

Its every element will be an array with a value from your array as value.

And key as the string file.

$arr = array();
foreach ($data as $elem) {
  $arr[] = array('file' => $elem);
}

Try debugging if you get the correct array:

echo '<pre>';
print_r($arr);
echo '</pre>';

Lastly,

echo json_encode($arr);
exit;

Hope it works for you.

Sign up to request clarification or add additional context in comments.

Comments

1

Use

$data = array_map(
    function ($item) {
        return array('file' => $item);
    },
    $data
);

to embed the values into arrays, or

$data = array_map(
    function ($item) {
        $x = new stdClass();
        $x->file = $item;
        return $x;
    },
    $data
);

to embed them into objects.

Or, better, use your own class instead of stdClass() and pass $item as argument to its constructor

$data = array_map(
    function ($item) {
        return new MyClass($item);
    },
    $data
);

Comments

0
$data = ["error.png", "invoice_1.pdf", "invoice2.png"];
$newarray = array();
foreach ($data as $val){
    array_push($newarray, array("file" => $val));
}
print_r($newarray); //Array ( [0] => Array ( [file] => error.png ) [1] => Array ( [file] => invoice_1.pdf ) [2] => Array ( [file] => invoice2.png ) )
echo json_encode($newarray); // [{"file":"error.png"},{"file":"invoice_1.pdf"},{"file":"invoice2.png"}]
exit;

Just try this logic

Comments

0
$data = '["error.png","invoice_1.pdf","invoice2.png"]';
$data = json_decode($data);
$data = array_filter($data, function(&$item){return ($item = array('file' => $item));});
$data = json_encode($data);

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.