How to read an Array and save - php

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/>';
}

Related

PHP How to echo a 3-dim array

After searching for an answer in this forum I found only related questions but under other context that would not apply to my case. Here's my problem:
I have a 3-dim array defined in a function like this:
$m_Array[h][$family][$iterator]
the values for
$family range from 6-10;
$iterator from 0-3 but has duplicates (0,1,2,3,1),
and the $m_Array results in values (25,26,30,31,33).
I am unable to echo the result using those indices to get these results once returned from the function.
NOTE: I was able to echo when I had 2-dim $m_Array[h][$iterator] but could not use it because the last value for the iterator would replace the second in the array.
Since I was able to echo the 2-dim, this is not a question on getting the return from the function or iterate over the indices.
Thanks.
Use print_r($arrayName) to print an array. You cannot echo an Array or Object
as others mentioned, you can use var_dump() or print_r(). If you need to access each item then you're going to need nested loops.
foreach($m_Array as $i => $h)
{
//echo $i, $key for h
foreach($h as $j => $family)
{
//echo $j, key for family
foreach($family as $k => $iterator)
{
echo $iterator;
}
}
}
try this:
$keys = array_keys($h);
for($i = 0; $i < count($h); $i++) {
echo $keys[$i] . "{<br>";
foreach($h[$keys[$i]] as $key => $value) {
echo $key . " : " . $value . "<br>";
}
echo "}<br>";
}
It prints all values and keys

Arrays and nested foreach

I have two array output (using preg_match_all), for example: $name[1] and $family[1].
i need to put these arrays together, and i use foreach as this:
foreach( $name[1] as $name) {
foreach( $family[1] as $family) {
echo $name.$family.'<br />';
}
}
but it don't work.
(each foreach loop works separately)
Assuming they have matching keys for the loop:
foreach( $name as $key => $value) {
echo $value[$key] . $family[$key] . '<br />';
}
This will go through each match for $name and print it out, and then print out the corresponding $family with it. I don't think you want to hardcode [1].
If you do, I'm a little confused and would like to see a var_dump of both $name and $family for clarification.
$together= array();
foreach( $name as $key => $n) {
$tuple= array('name'=>$name[$key],'family'=>$family[$key]);
$together[$key]= $tuple;
}
foreach( $together as $key => $tuple) {
echo "{$tuple['name']} {$tuple['family']}<br />";
}
Use array_combine():
Creates an array by using the values from the keys array as keys and
the values from the values array as the corresponding values.
PHP CODE:
$nameFamilly=array_combine($name[1] , $family[1]);
foreach( $nameFamilly as $name=>$familly) {
echo $name.$family.'<br />';
}

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

How to echo out the values of this array?

How to echo out the values individually of this array?
Array ( [0] => 20120514 [1] => My Event 3 )
so
echo $value[0]; etc
I have this so far:
foreach (json_decode($json_data_string, true) as $item) {
$eventDate = trim($item['date']);
// positive limit
$myarray = (explode(',', $eventDate, 2));
foreach ($myarray as $value) {
echo $value;
}
This echo's out the whole string no as an array. and if i do this?
echo $value[0};
Then I only get 2 characters of it??
The print_r :
Array ( [0] => 20120430 [1] => My Event 1 )
foreach ($array as $key => $val) {
echo $val;
}
Here is a simple routine for an array of primitive elements:
for ($i = 0; $i < count($mySimpleArray); $i++)
{
echo $mySimpleArray[$i] . "\n";
}
you need the set key and value in foreach loop for that:
foreach($item AS $key -> $value) {
echo $value;
}
this should do the trick :)
The problem here is in your explode statement
//$item['date'] presumably = 20120514. Do a print of this
$eventDate = trim($item['date']);
//This explodes on , but there is no , in $eventDate
//You also have a limit of 2 set in the below explode statement
$myarray = (explode(',', $eventDate, 2));
//$myarray is currently = to '20'
foreach ($myarray as $value) {
//Now you are iterating through a string
echo $value;
}
Try changing your initial $item['date'] to be 2012,04,30 if that's what you're trying to do. Otherwise I'm not entirely sure what you're trying to print.
var_dump($value)
it solved my problem, hope yours too.

Php pushing values to a 2-dimensional array

i've a 2-dimensional array and i want to push values to it with a while loop like;
$arr[0][1] = 1. value
$arr[0][2] = 2. value
i ve tried
while($zRow = mysql_fetch_array($zQuery))
{
$props[]['name'] =$zRow['name'];
$props[]['photo'] =$zRow['thumbnail'];
}
this loop pushes name to $props[0][name] and thumbnail to $props[1][photo]
i also tried
$j = 0;
while($zRow = mysql_fetch_array($zQuery))
{
$props[$j]['name'] =$zRow['name'];
$props[$j]['photo'] =$zRow['thumbnail'];
$j+=1;
}
that works but with this i when i use foreach loop later, it makes trouble like "Illegal offset type"
and here is my foreach loop
foreach($props as $no)
{
echo $props[$no]['name'];
}
now my questions;
1) are there any other way than while loop with $j variable like array_push for 2-dimensional arrays
2)how can i use foreach loop for 2-dimensional arrays
You could change the first loop to the following:
while($zRow = mysql_fetch_array($zQuery))
{
$row = array();
$row['name'] = $zRow['name'];
$row['photo'] = $zRow['thumbnail'];
$props[] = $row;
}
Your method also works, but you need that extra variable.
In your second loop, what you actually need to be doing is:
foreach($props as $index => $array)
{
echo $props[$index]['name'];
// OR
echo $array['name'];
}
Pushing anything onto an array with $myArray[] = 'foo' will increment the array's counter.
For multidimensional array, you need to populate the "inner" array, then push it to the "outer" (in your case $props) array.
while($zRow = mysql_fetch_array($zQuery)) {
$data = array('name' => $zRow['name'], 'photo' => $zRow['thumbnail']);
$props[] = $data;
}
To iterate over multidimensional arrays whose depth is known:
foreach ($props as $prop) {
foreach ($prop as $key => $value) {
echo "{$key} => {$value}" . PHP_EOL;
}
}
If the depth of the nesting is not known, you may have to use a recursive function to gather the data.

Categories