PHP Parse $_POST Array? - php

A server sends me a $_POST request in the following format:
POST {
array1
{
info1,
info2,
info3
},
info4
}
So naturally, I could extract the info# very simply with $_POST['#info'].
But how do I get the the three info's in the array1?
I tried $_POST['array1']['info1'] to no avail.
Thanks!
a:2: {s:7:"payload";s:59:"{"amount":25,"adjusted_amount":17.0,"uid":"jiajia"}";s:9:"signature";s:40:"53764f33e087e418dbbc1c702499203243f759d4";}
is the serialized version of the POST

Use index notation:
$_POST['array1'][0]
$_POST['array1'][1]
$_POST['array1'][2]
If you need to iterate over a variable response:
for ($i = 0, $l = count($_POST['array1']); $i < $l; $i++) {
doStuff($_POST['array1'][$i]);
}
This more or less takes this shape in plain PHP:
$post = array();
$post['info'] = '#';
$post['array1'] = array('info1', 'info2', 'info3');
http://codepad.org/1QZVOaw4
So you can see it's really just an array in an array, with numeric indices.
Note, if it's an associative array, you need to use foreach():
foreach ($_POST['array1'] as $key => $val) {
doStuff($key, $val);
}
http://codepad.org/WW7U5qmN

try
$_POST['array1'][0]
$_POST['array1'][1]
$_POST['array1'][2]

You can simply use a foreach loop on the $_POST
foreach($_POST["array1"] as $info)
{
echo $info;
}
or you can access them by their index:
for($i = 0; $i<sizeof($_POST["array1"]); $i++)
{
echo $_POST["array1"][$i];
}

Related

how can i get the data from this array in php?

I have the following code..
$array_test = array();
for($i = 0;$i<5;$i++) {
array_push($array_test,array("result".$i=>"exist_data".$i));
}
for($j = 0; $j<count($array_test);$j++) {
echo $array_test[$j];
}
var_dump($array_test); // the data exist
but the loop for only show me ArrayArrayArrayArray
thanks for help.
echo $array_test[$j]; would not work because you have a 2D array and can't access the variables of 2D array in that way. This would throw Array to String Conversion error.
Change your code to :-
for($j = 0; $j<count($array_test);$j++) {
echo $array_test[$j]["result".$j] ."<br>";
}
Output
exist_data0
exist_data1
exist_data2
exist_data3
exist_data4

How to read an Array and save

I'm trying to read an array to save some values but it doesnt work! Here's my code:
$array=$_POST['idprod'];//I get my array and save it on a var
print_r($array); //It has ALL the data (I use a print_r($array); And YES!! It has the information i need)
$ids[]=explode(',',$array);//Substring to my var
for( $contador=0; $contador <count($ids); $contador++ )
{
echo $ids[$contador].'<br/>';
}
It shows me Array to string conversion in...
What could I do?
use foreach Instead for loop
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
foreach ($array => $var ) {
// do any thing
}
replace
$ids[]=explode(',',$array);//Substring to my var
for( $contador=0; $contador <count($ids); $contador++ ) {
echo $ids[$contador].'<br/>';
and set
$ids = explode(',',$array);
foreach($ids as $id) {
echo $id ."<br>";
}
You only need to explode(), if the incomming data is a comma separated string.
$string = $_POST['idprod'];
$array= explode(',', $string); // split the comma separated values into an array
for($i=0; $i<count($array); $i++)
{
echo $array[$i] . '<br/>';
}
Else you can directly work with the incomming array:
$array = $_POST['idprod'];
for($i=0; $i<count($array); $i++)
{
echo $array[$i] . '<br/>';
}

Send and Decode Object Array via JSON

I have an array of People objects. I'm sending them to PHP but the way to get my objects back in PHP so I can manipulate them seems convoluted. Here's what I have, but it doesn't seem to return anything back to my AJAX Call. Right now I just have 1 Person Object in my array but I want to make sure everything is fine before I advance. In short, when I decode my JSON shouldn't it convert it to an Object in PHP? In the end I want an array of PHP objects that are People
Jquery
var people = new Array();
var person = new Person("Michael", "Jackson", 50);
localStorage.setItem(person.firstName + " " + person.lastName, JSON.stringify(person));
function Person(firstName, lastName, age)
{
this.firstName=firstName;
this.lastName=lastName;
this.age=age;
}
function getStorage(){
var tempPerson;
for(var i = 0; i < localStorage.length; i++)
{
tempPerson = $.parseJSON(localStorage.getItem(localStorage.key(i)));
people.push(tempPerson);
}
}
function getPeople(){
$.post(
"people.php",
{people : people},
function(data)
{
alert(data);
}
);
}
getStorage();
getPeople();
PHP
<?php
$personObj = Array();
$people = $_POST['people'];
for($i = 0; $i < count($people); $i++)
{
foreach($people[$i] as $person)
{
$streamObj = json_decode($person);
}
}
echo $personObj->$firstName;
In addition to making the change suggested by #Even Hahn, you need to change the data you are posting as follows:
$.post(
"people.php",
{people : JSON.stringify(people)},
function(data)
{
alert(data);
}
);
This way a single name/value pair is posted. The name is "people" and the value is a JSON encoded string of the array of Person objects.
Then when you call the following in the PHP code, you are decoding that JSON encoded string into an array on the PHP side.
$people = json_decode($_POST['people']);
I also see where you assign $personObj to an array, but I don't see where you put anything in the array.
Try moving your JSON decoding in your PHP:
$personObj = Array();
$people = json_decode($_POST['people']);
for($i = 0; $i < count($people); $i++)
{
foreach($people[$i] as $person)
{
$streamObj = $person;
}
}
echo $personObj->$firstName;
This is because $_POST['people'] is a JSON string which needs to be decoded.
Perhaps the PHP codes should be look like this:
<?php
$personObj = Array();
$people = $_POST["people"];
foreach($people as $p)
{
$val = str_replace("\\","",$p);
$personObj = json_decode($val);
}
echo $personObj->firstName;
?>

loop through an array and show results

i m trying to do a loop but get stacked ,
i have a function that convert facebook id to facebook name , by the facebook api. name is getName().
on the other hand i have an arra with ids . name is $receivers.
the count of the total receivers $totalreceivers .
i want to show names of receivers according to the ids stored in the array.
i tried every thing but couldnt get it. any help will be appreciated . thanks in advance.
here is my code :
for ($i = 0; $i < $totalreceivers; $i++) {
foreach ( $receivers as $value)
{
echo getName($receivers[$i]) ;
}
}
the function :
function getName($me)
{
$facebookUrl = "https://graph.facebook.com/".$me;
$str = file_get_contents($facebookUrl);
$result = json_decode($str);
return $result->name;
}
The inner foreach loop seems to be entirely redundant. Try something like:
$names = array();
for ($i = 0; $i < $totalReceivers; $i++) {
$names[] = getName($receivers[$i]);
}
Doing a print_r($names) afterwards should show you the results of the loop, assuming your getNames function is working properly.
Depending of the content of the $receivers array try either
foreach ($receivers as $value){
echo getName($value) ;
}
or
foreach ($receivers as $key => $value){
echo getName($key) ;
}

how to read an complex array in PHP

How to read the array below. For example i would like to set the 'actual_cash' to some other value. PLease help I am new to PhP.
$Cashups[0]['actual_cash'] = 50.22;
To change the first instance of actual_cash.
$Cashups[1]['actual_cash'] = 100.22;
To chance the second instance, and so on.
To loop through this array, you can do something like:
foreach($Cashups as &$c)
{
$c['actual_cash']=500.00;
}
Which would change al the actual_cash instances to 500.00
You can use foreach to iterate array
foreach($Cashups as $key => $value)
{
$value['actual_cash']='newval';
}
if you have only two items in array you could also do this
$Cashups[0]['actual_cash']='someval';
$Cashups[1]['actual_cash']='someval';
foreach($Cashups as $item){
$item['actual_cash'] = $mynewvalue;
}
using for loop:
for($i = 0; $i < count($Cashups); $i++) {
$Cashups[$i]['actual_cash'] = $yourValue;
}
using foreach loop:
foreach($Cashups as &$c) {
$c['actual_cash'] = $yourValue;
}
Try something like this
foreach($Cashups as &$cashup){
// referencing $cashup to change it's value
$cashup = 'new value';
}

Categories