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.

I wrote a javascript function which takes in a string and parses it as an associative array.

function getValues(string){
    var array_values = new Array();
    var pairs_array = string.split('\n');
    if(pairs_array[0] == 'SUCCESS'){
        window.success = true;
    }

    for(x=1; x< pairs_array.length; x++){
    var parsedValue = '';
    //console.log(pairs_array[x] + "<br>");
    var pair = pairs_array[x].split('=');
    //console.log(pair[1]);
    var variable = pair[0];
        if(pair[1]){
        var value = pair[1];
        for(i=0; i< value.length; i++){

            var character = value.charAt(i);

            if(character == '+'){
                parsedValue = parsedValue + character.replace('+', ' ');    
            }else{
                parsedValue = parsedValue + value.charAt(i);
            }   
        }

        array_values[variable] = decodeURIComponent(parsedValue);
        }else{
        array_values[variable] = '';

        }
    }
return array_values;


}

Then the function is called on the string window.name_value_pairs as follows

var array_callback = getValues(window.name_value_pairs);
    for(x in array_callback){
    console.log("call" + x + " " + array_callback[x]);


}

Works fine. Now i have been trying to write the function in php because i would prefer it on the server side but it is not working out. I'm not sure if the array values ar getting pushed onto the array because nothing gets returned. heres the php code i have tried: Note: $results_values is a string

$result_values = $_REQUEST['result_values'];
echo "php array " . getValuesPhp($result_values);

function getValuesPhp($string){
    $array_values = array();
    $pairs_array = explode("\n",$string);
        if($pairs_array[0] == 'SUCCESS'){
            $success = true;
            echo "TRUE";
        }
        for($x=1; $x< count($pairs_array); $x++){
            $parsedValue = '';

            $pair = explode("=",$pairs_array[$x]);

            $variable = $pair[0];

            if(isset($pair[1])){
                $value = $pair[1];

                for($i=0; $i< strlen($value); $i++){

                    $character = $value[$i];

                    //echo "char \n" . $character;
                    if(strpos($character, '+') !== false){
                        //echo "plus";
                        $parsedValue .= str_replace('+', ' ', $character);  
                    }else{
                        //echo "hi2";
                        $parsedValue .= $value[$i];
                    }   
                }
                echo "\n var " . $variable;
                echo "\n parsed " . $parsedValue;

                $array_values['" . $variable . "'] = $parsedValue;
                //echo "arrayValues " . $array_values['" . $variable . "'];
                //array_push($GLOBALS[$array_values]['" . $variable . "'], $parsedValue);
            }else{
                $array_values['" . $variable . "'] = '';
                //array_push($GLOBALS[$array_values]['" . $variable . "'], '');

            }
        }
        //echo "array payment stat" . $array_values['payment_status'];
        return $array_values;
}

note: where it says $array_values['" . $variable . "'] this does print out the write result as it goes through the loop however it seems like the array elements are not being added to the array as nothing is returned at the end. Thanks for any help Sarah Update: @ChrisWillard I would like to return an associative array from the string. the string is in the format where each line is in the form key=value .. it is actually the string which comes back from a paypal pdt response. For example:

SUCCESS
mc_gross=3.00
protection_eligibility=Eligible
address_status=confirmed
item_number1=3
tax=0.00
item_number2=2
payer_id=VWCYB9FFJ
address_street=1+Main+Terrace
payment_date=14%3A26%3A14+May+22%2C+2014+PDT
payment_status=Completed
charset=windows-1252
address_zip=W12+4LQ
mc_shipping=0.00
mc_handling=0.00
first_name=Sam
address_country_code=GB
address_name=Sam+Monks
custom=
payer_status=verified
business=mon%40gmail.com
address_country=United+Kingdom
num_cart_items=2
mc_handling1=0.00
mc_handling2=0.00
address_city=Wolverhampton
payer_email=monks%40gmail.com
mc_shipping1=0.00
mc_shipping2=0.00
tax1=0.00
tax2=0.00
txn_id=3PX5572092U
payment_type=instant
last_name=Monks
address_state=West+Midlands
item_name1=Electro
receiver_email=mon%40gmail.com
item_name2=Dub
quantity1=1
quantity2=1
receiver_id=WHRPZLLP6
pending_reason=multi_currency
txn_type=cart
mc_gross_1=1.00
mc_currency=USD
mc_gross_2=2.00
residence_country=GB
transaction_subject=
payment_gross=3.00

thanks for all your answers and help. it was a combination of two things that caused it to not print.. firstly my silly syntax error (being just new at programming haha I wont go into the logic i had behind this but it did make sense to me at the time haha) $array_values['" . $variable . "'] = $parsedValue; changed to this: $array_values[$variable] = $parsedValue; it was also the line echo "php array" . getValuesPhp($result_values); that caused it not to print. when i changed this to print_r(getValuesPhp($result_values)); it printed perfect thanks to @ChrisWillard for this. So here is my final code. A combination of @ChrisWillard answer and @Mark B and @Jdo answers. I also wanted to check first if pair[1] existed and go through each character of pair[1] changing any '+' to a space ' ' if it existed so that it could be read by the user. Now i have found the function to do this for me haha. I'm sure it is not new information for a lot of you but for anyone who doesn't know it is urldecode so you can see below ive commented out the loop that i did not need (going through the characters of the string changing the plus value) and instead ive written: $finished_array[$key] = urldecode($value); thanks for all your help.

$result_values = $_REQUEST['result_values'];
print_r(getValuesPhp($result_values));


function getValuesPhp($string){
    $finished_array = array();
        $pairs_array = explode("\n",$string);
        if($pairs_array[0] == 'SUCCESS'){
            $success = true;
            //echo "TRUE";
        }
    for($x=1; $x< count($pairs_array); $x++){
        $parsedValue = '';

        $pair = explode("=",$pairs_array[$x]);
        $key = $pair[0];
        if(isset($pair[1])){
            $value = $pair[1];

            //for($i=0; $i< strlen($value); $i++){
                //$character = $value[$i];
                //if(strpos($character, '+') !== false){
                    //$parsedValue .= str_replace('+', ' ', $character);    
                //}else{    
                    //$parsedValue .= $value[$i];
                //} 
            //}

            $finished_array[$key] = urldecode($value);

        }else{
            $finished_array[$key] = ''; 

        }
    }
    return $finished_array;
}
share|improve this question
    
And you get no syntax error on that line? Use array_values[$variable] = $parsedValue; instead. –  jdo May 23 at 16:56
    
Do you want to return an array or a string from the getValuesPhp function? It looks like you're building an array, but you're echoing the return value. What do you get when you do print_r(getValuesPhp($result_values)); ? –  EatPeanutButter May 23 at 17:02
    
Please give an example (source) string. –  dcromley May 23 at 17:05
    
@jdo thanks. no i dont get a syntax error and it prints out the right values but i have tried what you suggested and it also prints out correct like this: $array_values[$variable] = $parsedValue; echo "arrayValues " . $array_values[$variable]; but i still have the final problem. –  Sarah May 23 at 17:10
    
You should really switch on 'error_repoting'. –  jdo May 23 at 17:18

2 Answers 2

up vote 0 down vote accepted

From what I can gather, this should get you what you need:

$result_values = $_REQUEST['result_values'];
print_r(getValuesPhp($result_values));

function getValuesPhp($string){
    $finished_array = array();
    $pairs_array = explode("\n",$string);

        if($pairs_array[0] == 'SUCCESS'){
            $success = true;   ////Not sure what you're trying to do here
        }

    for($x=1; $x< count($pairs_array); $x++)  {

        $pair = explode("=",$pairs_array[$x]);
        $key = $pair[0];
        $value = $pair[1];
        $finished_array[$key] = $value;

    }
        return $finished_array;
}
share|improve this answer
    
thanks for your answer. I'm sorry i have to rush away from my computer now. I will try this and get back to you tomorrow. I will just point out that i only want to add the key/value pair to the finished array if pair[1] exists in the current iteration of the loop as in some cases it does not exist. ie in the original string you will find custom= also I wanted to parse pair[1] further by going through the characters of pair[1] and replacing a '+' with a ' ' space and also urldecoding the string. But i will try work with what you gave me to do this tomorrow. Thanks a mil. –  Sarah May 23 at 17:49
    
Thanks for your answer. it was the print_r that helped it work. echo didnt print out the array. and also as i said just above that i wanted to go through the value in each element and change the plus to a space, effectively decoding it, I found the function to do that urldecode so I added that instead of the small loop i had iterating through each character. Thanks for your help. As a newbie I appreciate it very much :) haha you can see my full final code above –  Sarah May 24 at 15:57

This is totally non-sensical:

            $array_values['" . $variable . "'] = $parsedValue;

You're literally using " . $variable . " as your array key - remember that '-quoted strings do NOT expand variables.

Why not just

$array_values[$variable] = $parsedValue
share|improve this answer
    
thanks for pointing out this error. this was indeed part of the problem which is probably quite obvious for experienced programmers. haha. The other part of the problem was that echo did not print out the array i needed print_r instead. thanks a lot for your help. –  Sarah May 24 at 16:01

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.