how can i get the data from this array in php? - 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

Related

Strict Standards error, trying to reverse a string as array

So I have a string with comma separated values:
$accounts = "1,2,3,4,5,6";
And I want to reverse that order. So I wrote this:
$accountsrev = implode(',',rsort(explode(',',$accounts)));
Basically I convert to an array, reverse the array, and implode it back into a string. What's wrong with that?
I get a load of errors like this:
Strict Standards: Only variables should be passed by reference in /home/username/public_html/file.php on line 121
Warning: implode(): Invalid arguments passed in /home/username/public_html/file.php on line 121
Edit:
Now I wonder if the way I build the $accounts variable is wrong. I pull 7 rows from the database and then build the $accounts variable in a while loop. The id is an integer in the database:
$accounts = '';
$i = 1;
while ($data = $getdata->fetch(PDO::FETCH_ASSOC)) {
if ($i < 7) {
$accounts .= $data['id'].',';
} else {
$accounts .= $data['id'];
}
$i++;
}
Does the way I make the $accounts variable not produce a string?
This is just something that tells you you're doing something completely wrong:
$array = [1,2,3,4];
rsort($array);
//$array is sorted.
However:
rsort(array_filter($array));
//Array filter returned a copy of the original array so $array is neither sorted nor filtered.
You need to do:
$accounts = '';
while ($data = $getdata->fetch(PDO::FETCH_ASSOC)) {
$accounts .= $data['id'].',';
}
$accountsrev = explode(',',rtrim($accounts,","));
rsort($accountsrev);
$accountsrev = implode(',',$accountsrev);//accountsrev is sorted here
<?php
$accounts = '';
$i = 0;
while ($data = $getdata->fetch(PDO::FETCH_ASSOC)) {
$i++;
if($i == 1){
$accounts = $data['id'];
} else {
$accounts .= $data['id'].',';
}
}
$accountsrev = explode(',',$accounts); // explode it as make array
rsort($accountsrev); // then use rsort which sort array reverse
$accountsrev = implode(',',$accountsrev); // again implode it
echo $accountsrev;
?>
then output will be
6,5,4,3,2,1
or you can use array_reverse () function instead rsort
echo $accountsrev = implode(',',array_reverse(explode(',',$accounts)));
then output will be
6,5,4,3,2,1
Quick and easy:
$accounts = '1,2,3,4,5,6';
echo $accountsrev = implode(',',array_reverse(explode(',',$accounts)));

Array not repeating inside in for loop

I have an array for autofilled multi select form. I have to display some values as initial values, And I have an array for it.
This is my code.
for($i=0; $i<count($temp_multy_name); $i++)
{
echo $temp_multy_name[$i]; echo"&nbsp";
$pac->set_init_selection(array(
array("id"=>"$temp_multy_name[$i]", "text"=>"$temp_multy_name[$i]"),
));
}
when I run echo $temp_multy_name[$i], i get php and mysql, but when I apply it in the set_init_selection i got only the last value, Don't know why. Can any one please help me?
Here is your solution
$setInitSelection = array();
for($i=0; $i<count($temp_multy_name); $i++)
{
echo $temp_multy_name[$i]; echo"&nbsp";
$setInitSelection[] = array("id"=>$temp_multy_name[$i], "text"=>$temp_multy_name[$i]);
}
$pac->set_init_selection($setInitSelection);
Maybe you are overriding your array. Try this:
$selection_array = array();
for($i=0; $i<count($temp_multy_name); $i++)
{
//echo $temp_multy_name[$i]; echo"&nbsp";
$selection_array[] = array("id"=>$temp_multy_name[$i], "text"=>$temp_multy_name[$i]);
}
$pac->set_init_selection($selection_array);
Your calling the $pac->set_init_name(array $val) multiple times, overwriting the previous values. Try this:
$initialSelection = array();
for($i=0; $i<count($temp_multy_name); $i++)
{
echo $temp_multy_name[$i]; echo"&nbsp";
$initialSelection[$i] = array("id"=>$temp_multy_name[$i], "text"=>$temp_multy_name[$i]);
}
$pac->set_init_selection(array($initialSelection);
Hope that helps.

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;
?>

PHP Parse $_POST Array?

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];
}

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) ;
}

Categories