简体   繁体   中英

How to convert a string containing an array value to a PHP array?

I have a string that contains an array like:

$tarray = Array ( [gt_ref_id] => 36493115 [tender_notice_type] => [organisation_name] => ROSALES WATER DISTRICT [address] => No. 5 Bonifacio Street [address2] => [contact_person] => [tender_notice_no] => ROSALWD 2016-011-0144(Ref: 4206661)
)

but I want to access the value of this array like:

echo "ref id = ".$tarray['gt_ref_id'];

It should output like:

ref id = 36493115

but I can't because it's a string. I could if it was an array.

How can I convert the string to a proper PHP array?

If you want store a php array on you database you can try with json_encode or serialize , and when you would need retrive data from you database, you can use json_decode or unserialize .

Using JSON

Examples(store as json):

$myArray = array('name' => 'Jack', 'lastname' => 'Smith', 24);
$toStore = json_encode($myArray); // return a string: {"name":"Jack","lastname":"Smith","0":24}

mysqli_query($link,
    'INSERT INTO myTable (data)
    VALUES ("' . mysqli_real_escape_string($link, $toStore) . '")'
);

Examples(retrieved from json):

$query = mysqli_query($link, 'SELECT FROM MyTable WHERE id = ...');
$row = mysqli_fetch_assoc($query);
$row = json_decode($row); // return a array: array('name' => 'Jack', 'lastname' => 'Smith', 24)

Using serialize

Example(store serialized): $myArray = array('name' => 'Jack', 'lastname' => 'Smith', 24); $toStore = serialize($myArray); // return a string: a:3:{s:4:"name";s:4:"Jack";s:8:"lastname";s:5:"Smith";i:0;i:24;}

mysqli_query($link,
    'INSERT INTO myTable (data)
    VALUES ("' . mysqli_real_escape_string($link, $toStore) . '")'
);

Examples(retrieve serialized):

$query = mysqli_query($link, 'SELECT FROM MyTable WHERE id = ...');
$row = mysqli_fetch_assoc($query);
$row = unserialize($row); // return a array: array('name' => 'Jack', 'lastname' => 'Smith', 24)

After :

if you need access to you data from converted array, you can call like:

$row['name'] // return "Jack"

Another ways

Regexp:

You can try use regexp, but this not the best way because sometime is too slow to process data, and maybe, if you don't know security aspects, this definitely not is the best way.

Tokenizer:

You can try create you own token processor, like template engine, but this is the most large way...

Learn more about the functions:

Pros:

  1. Support multiple data-types: multidimentional array , object , integer , float , string , and many more data except resource .
  2. Native support for serialize and unserialize since PHP4.
  3. Native support for json_encode and json_decode since PHP 5.2.0
  4. Fast and secure encode and decode.

As suggested by Olaf Erlandsen you should probably store your array in another format -- serialized or as a json dump. I'd prefer the latter.

However, chances are that you're not the one generating this (rather odd) string. It may be provided by someone else. In that case you could use a regular expression (RegEx) to extract the keys and values of the array.

You can use preg_match_all() to match them and then loop over the matches to join them into an array. I find it easier to loop over the results when the PREG_SET_ORDER flag is set.

Example code:

$string = "Array ( [gt_ref_id] => 36493115 [tender_notice_type] => hiha [organisation_name] => ROSALES WATER DISTRICT [address] => No. 5 Bonifacio Street [address2] => [contact_person] => [tender_notice_no] => ROSALWD 2016-011-0144(Ref: 4206661))";
$string = substr( $string, 8 ); # Strip Array ( , from beginning of string.
$string = substr( $string, 0, - 1 ); # Strip last ) from string.

preg_match_all( "/\[(.*?)\] => ([^\[]*)/", $string, $matches, PREG_SET_ORDER );

foreach ( $matches as $match ) {
    $tarray[ $match[1] ] = substr( $match[2], 0, - 1 );
    # Note that $match[2] contains a trailing white-space, stripping it with substr().
    # On another note, you should probably check whether $match[2] has any content.
}

var_dump($tarray);

I put the pattern up on regex101, that'll probably make things clearer if you're new to these patterns .

Note: I'm not exactly a RegEx-genious, maybe someone can check the pattern I provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM