0

I have a string like this:

 0: array( 'name' => 'john', 'username' => 'foo' ) 1: array( 'name' => 'jack', 'username' => 'foo' )"

how I can encode it in json? I tried with:

$value = array_values($arr);
var_dump($value);

but I get NULL

UPDATE - If I do json_encode($arr); I get:

 ""\r\n 0: array(\r\n 'name' => 'john',\r\n 'username' => 'foo'\r\n )\r\n 1: array(\r\n 'name' => 'jack',\r\n 'username' => 'foo'\r\n )""
8
  • @JayBlanchard there is a problem with json_encode I get a bad encoding, check the update question. Commented Feb 26, 2016 at 15:49
  • How is your array built? It's encoding it like a string instead of an array. Commented Feb 26, 2016 at 15:53
  • @aynber how you can see in my first code, my array have space internally. Commented Feb 26, 2016 at 15:53
  • Let me rephrase: how did you create and build your array? Is it being passed from a form or database, or are you creating it within your code? Commented Feb 26, 2016 at 15:54
  • 1
    Your "array" is really a string, and it won't encode as an array. I'd suggest building a correct array, then you can use it with json_encode. Commented Feb 26, 2016 at 15:57

1 Answer 1

3

Take a look at json_encode php function. I believe this is what you're looking for.

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);
?>
Sign up to request clarification or add additional context in comments.

4 Comments

Can you update with the line where you defined the array?
Uhm it's difficult for me, I have a lot of function for encode the array.. Anyway this is the function that return the array with space: pastebin.com/AWW2UZMb
The variable that your calling json_encode with is not an array. Looks like a string. Am I seeing this correctly?
Yes sorry for the error the function return a string not an array, let met correct the title.

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.