1

I have this json string:

$row['medium'] = "{\"medium\":13|17|1|14, \"medium_sub\":21}";

now I want to make an array from the "medium" part:

$medium_arr = $row['medium']->{'medium'};   

$medium_arr =
explode("|", $medium_arr);

print_r($medium_arr); //This is empty

when I make an array with zero's like (but I know, this makes no sense)

$row['medium'] = "{\"medium\":1301701014, \"medium_sub\":21}";
$medium_arr = explode("0", $medium_arr);

print_r($medium_arr); //This gives 4 results

how is it possible that I can not use the explode in a proper way?

2
  • 1
    Are you leaving out some json_decode and other operations in your actual code, or just in this question? Commented Mar 30, 2012 at 14:09
  • yes indeed, I did skip the json_decode /json_encode lines, sorry, I should have mentioned that Commented Mar 30, 2012 at 18:15

2 Answers 2

4

If that is your real JSON string, it isn't valid. The pipe-delimited string must be quoted. Using zeros worked because it resulted in a numeric value for medium that didn't need quotes.

$row['medium'] = "{\"medium\":\"13|17|1|14\", \"medium_sub\":21}";

It can then be decoded properly with json_decode().

var_dump(json_decode($row['medium']));
object(stdClass)#1 (2) {
  ["medium"]=>
  string(10) "13|17|1|14"
  ["medium_sub"]=>
  int(21)
}

$json = json_decode($row['medium']);
$medium_arr = $json->medium;
$medium_arr = explode("|", $medium_arr);
var_dump($medium_arr);

array(4) {
  [0]=>
  string(2) "13"
  [1]=>
  string(2) "17"
  [2]=>
  string(1) "1"
  [3]=>
  string(2) "14"
}

Update

I would add that instead of using a delimited string, if you have the ability to modify the JSON, you ought to use an array for those values in the JSON as:

$row['medium'] = "{\"medium\":[13,17,1,14], \"medium_sub\":21}";
var_dump(json_decode($row['medium]));

// Now they're already an array!
object(stdClass)#1 (2) {
  ["medium"]=>
  array(4) {
    [0]=>
    int(13)
    [1]=>
    int(17)
    [2]=>
    int(1)
    [3]=>
    int(14)
  }
  ["medium_sub"]=>
  int(21)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Michael, sorry I didn't responded earlier -(new house, new workspace)- thank you for the quote-advice, that made it to work! - Regards
0

Try this.

    $row['medium'] = "{\"medium\":13|17|1|14, \"medium_sub\":21}";

    $medium_arr = $row['medium'];

    $medium_arr = json_decode($medium_arr);

    print_r($medium_arr);

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.