I have an array (POSTed from a Python application) called "observations". It looks like this:
Array
(
[0] => Array
(
['remote_id'] => 1
['dimension_id'] => 1
['metric'] => 1
)
[1] => Array
(
['remote_id'] => 1
['dimension'] => 2
['metric'] => 2
)
[2] => Array
(
['remote_id'] => 1
['dimension_id'] => 3
['metric'] => 3
)
(etc)
I want to iterate through all those instances of remote_id, dimension_id and metric and write them to a database. But I can't access them - here's my PHP:
foreach ($_POST["observations"] as $observation) {
echo "Let's try and access the whole array... \n";
print_r ($observation);
echo "But what about the sub elements? \n";
print_r ($observation[0]);
print_r ($observation['dimension_id']);
}
This returns:
Let's try and access the whole array...
Array
(
['remote_id'] => 1
['dimension_id'] => 1
['metric'] => 1
)
But what about the sub elements?
Let's try and access the whole array...
Array
(
['remote_id'] => 1
['dimension'] => 2
['metric'] => 2
)
But what about the sub elements?
(etc)
So my print_r ($observation[0]) and print_r ($observation['dimension_id']) are both failing to access the appropriate sub-elements and returning empty. What am I missing here?
Edit: a few questions about my (potentially malformed) POST. Doing it in Python like so:
data = urllib.urlencode([
("observations[0]['remote_id']", 1),
("observations[0]['dimension_id']", 1),
("observations[0]['metric']",metric1),
("observations[1]['remote_id']", 1),
("observations[1]['dimension']", 2),
("observations[1]['metric']", metric2),
("observations[2]['remote_id']", 1),
("observations[2]['dimension_id']", 3),
("observations[2]['metric']",metric3),
("observations[3]['remote_id']", 1),
("observations[3]['dimension_id']", 4),
("observations[3]['metric']",metric4),
("observations[4]['remote_id']", 1),
("observations[4]['dimension_id']", 5),
("observations[4]['metric']",metric5),
])
response = urllib2.urlopen(url=url, data=data)
$observation. Indexdimension_idexists and alsodimension- which is right?$observation['dimension_id']should work. Enable error reporting and you will get noticed for the wrong keysvar_dump(array_keys($observation)), then look at this. Seems like your POSTed keys have extra quotes and you need to use$observation["'metric'"]instead of the usual$observation['metric']. (Of course, the right solution would be to fix your POSTing code not to add those extra quotes in the first place.)