Thread: Parsing string

    #1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2005
    Location
    Vancouver, WA, USA
    Posts
    425
    Rep Power
    0

    Parsing string


    Say I had the following info in a single string:

    PHP Code:
    $appParams='{"casino":"Sun Monte Carlo","table":"blackjack123"}'
    Yet I want my result to be:

    PHP Code:
    $param['casino']="Sun Monte Carlo";
    $param['table']="blackjack123"
    The original string may have any number of pairs of data.

    What would be the easiest way to parse this? I have no talents with regular expressions (not that I'm sure regular expressions are the way to go)
  2. #2
  3. No Profile Picture
    I haz teh codez!
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Dec 2003
    Posts
    2,574
    Rep Power
    2343
    Looks like JSON, so
    php Code:
    <?php
     
    $appParams='{"casino":"Sun Monte Carlo","table":"blackjack123"}';
    $decoded=json_decode($appParams);
    var_dump($decoded);
     
    ?>

    yields:
    Code:
    php -f jsd.php 
    object(stdClass)#1 (2) {
      ["casino"]=>
      string(15) "Sun Monte Carlo"
      ["table"]=>
      string(12) "blackjack123"
    }

    Comments on this post

    • ttremain agrees : Thank you!
    I ♥ ManiacDan & requinix

    This is a sig, and not necessarily a comment on the OP:
    Please don't be a help vampire!
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2005
    Location
    Vancouver, WA, USA
    Posts
    425
    Rep Power
    0
    We are getting VERY close.


    PHP Code:
    <?php
    $appParams
    ='{"casino":"Sun Monte Carlo","table":"blackjack123"}';
    $decoded=json_decode($appParams);
    var_dump($decoded);
    ?>
    How do I use $decoded as an associative array?

    If I add:
    PHP Code:
    echo $decoded['casino']; 
    I get:
    Fatal error: Cannot use object of type stdClass as array in /home/homedir/public_html/test1.php on line X
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2005
    Location
    Vancouver, WA, USA
    Posts
    425
    Rep Power
    0
    I've answered my own question. I can parse it into an associative array like:

    PHP Code:
    $decoded=json_decode($appParams,True); 
    By adding the "True" as the second argument.

    Comments on this post

    • ManiacDan agrees : For answering your own question and posting the solution.

IMN logo majestic logo threadwatch logo seochat tools logo