PHP访问数组值的正确方法是什么

PHP访问数组值的正确方法是什么

问题描述:

This seems like a greenhorn question but I am having a hard time here.

I have an array of post values from a form posted via jquery, the $_POST["extra"] array is formatted via .serialize().

string(1) "0"
["tax"]=>string(1) "0"
["taxRate"]=>string(1) "0"
["itemCount"]=>string(1) "3"
["item_name_1"]=>string(17) "Detox Diet 1234®"
["item_quantity_1"]=>string(1) "2"
["item_price_1"]=>string(5) "32.95"
["item_options_1"]=>string(56) "thumb: /cb2014-II/img/products/DetoxDiet1234.jpg, pid: 3"
["item_name_2"]=>string(12) "Fiber 1234®"
["item_quantity_2"]=>string(1) "1"
["item_price_2"]=>string(2) "55"
["item_options_2"]=>string(52) "thumb: /cb2014-II/img/products/Fiber1234.jpg, pid: 4"
["item_name_3"]=>string(10) "eAc 1234®"
["item_quantity_3"]=>string(1) "2"
["item_price_3"]=>string(5) "42.95"
["item_options_3"]=>string(40) "pid: 27, thumb: img/products/eAC1234.jpg"
["extra"]=>string(465) "x_first_name=value&x_last_name=value&phone=xxx-xxx-xxxx&fax=&email=first.last%40domain.com&company=company&ccnumber=xxxxxxxxxxx&expMo=1&expYr=2016&cvv=&address1=address one&address2=&city=city&state=UT&zip=xxxxx&country=USA&addressee_firstName=&addressee_lastName=&shipping_address1=&shipping_address2=&shipping_city=&shipping_state=&shipping_zip=&shipping_country=&checkoutConfirm=1&x_amount=xx.xx&num_units=3&x_test_request=yes"
["testItem"]=>string(9) "test Item"
["check_out"]=>string(3) "Yes"
}

To access the posted values inside of "extra" is the correct syntax $newVar = $_POST['extra']['num_units']?

Because it seems like the values being printed to my screen are the first character of the first 'extra' field name, I am not using a loop to fetch the values just trying to set locally after sanitizing.

MY SOLUTION: parse_str($extra,$extraFields); No I can access the values like $extraFields['x_first_name']

See this http://www.php.net//manual/en/function.parse-str.php

$extras = array();
parse_str($_POST['extra'], $extras);
//now $extras holds all the info in a readable format

It looks like your 'extra' field is a url encoded query string. You will need to decode that string before you can access the inner properties as data (rather than a string):

parse_str(urldecode($_POST['extra']), $extras);

Now you should be able to access $extra['x_last_name']