Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

A shipping service is providing me with this weird text format response, after some research i found it is very close to a .net array and i am trying to convert to PHP so i can do something useful with it.

My questions:

  1. What is this format?
  2. Is there any PHP function i could use to parse it?

    City[0] = "Elghorashi";
    State[0] = "";
    ZipCode[0] = "";
    CCity[0] = "Elghorashi";
    CState[0] = "";
    CZipCode[0] = "";
    City[1] = "Abugibha";
    State[1] = "";
    ZipCode[1] = "";
    CCity[1] = "Abugibha";
    CState[1] = "";
    CZipCode[1] = "";
    

Thanks

share|improve this question
    
PHP variables and arrays have preceding $ symbol, unless those are constants.. –  I Can Has Kittenz Apr 15 at 12:45
    
That looks like a var_dump of a php array. Are you using a var_dump to output that or is that the raw value being returned? –  Joe Meyer Apr 15 at 13:05

1 Answer 1

up vote 1 down vote accepted

Here's a quick little snippit I whipped up to convert a string that looks like a PHP array into an actual PHP array. To be clear the $newArray variable is where the array is created to.

$string = 'City[0] = "Elghorashi"; State[0] = ""; ZipCode[0] = ""; CCity[0] = "Elghorashi"; CState[0] = ""; CZipCode[0] = ""; City[1] = "Abugibha"; State[1] = ""; ZipCode[1] = ""; CCity[1] = "Abugibha"; CState[1] = ""; CZipCode[1] = "";';
$string = substr($string, 0, -1);

$arr = explode('; ', $string);
$newArray = [];
foreach($arr AS $value){
    $keyVals = explode(' = ', $value);
    preg_match_all('/^(.*?)\[([0-9]+)\]$/', $keyVals[0], $matches);
    $value = is_string($keyVals[1]) ? substr($keyVals[1], 1, -1) : $keyVals[1];
    $newArray[$matches[2][0]][$matches[1][0]] = $value;
}
share|improve this answer
    
Thanks mate that worked! –  mmahgoub Apr 15 at 17:45

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.