Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 17 days ago.
Improve this question
I have a very simple form on my website.
I run this PHP to loop the form contents:
echo '<pre>';
var_dump($_POST);
echo '</pre>';
$i = 0;
foreach($_POST as $key => $value)
{
$i++;
echo $value[$i]['row_id'];
}
I get the below:
array(1) {
["data"]=> array(2) {
[1]=> array(2) {
["row_id"]=> string(5) "33714"
["sport"]=> string(8) "swimming"
}
[2]=> array(2) {
["row_id"]=> string(5) "33715"
["sport"]=> string(8) "football"
}
}
}
33714
My PHP only echoes the first row id 33714 instead of both rows.
I feel I'm missing something obvious here.
You're looping over the wrong thing and you're simultaneously using two different methods to loop over the same thing.
You set $i to 0
Your foreach loop reaches $_POST['data']
You change $i to 1
You access $_POST['data'][1]
You get to the end of the loop
You need to loop over what you actually want to loop over.
data is a fixed thing, so hard code that. Then loop over the array it contains.
Only use a $i variable if you are using a regular for loop.
When you use foreach you use the variable(s) you define inside it (in this case $key and $value).
foreach($_POST['data'] as $key => $value) {
echo $value['row_id']
}
Simply put, you need to loop the items of $_POST['data'] instead of just $_POST
echo '<pre>';
var_dump($_POST);
echo '</pre>';
foreach($_POST['data'] as $key => $item)
{
echo $key.':'. $item['row_id'];
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
The problem is actually, there is an array containing a number of arrays. I have to print the elements of one of the sub arrays named 'list'. But I have a problem to fetch the subarray while using foreach loop.
The following code is:
foreach($arr as $key => $value)
{
$arr1=$value[$list];
echo $arr1;
}
Your code should be:-
// declare second array outside loop
$arr1 = [];
foreach($arr as $key => $value)
{
// list is a key in $value array then you can access via below way
$arr1[] = $value['list'];
}
// print Array using print_r() function outside loop
print_r($arr1);
Hope it will help you :)
If your array like in below format
<?php
$arr = array(
'key' => array('array elements here'),
'list' => array('array elements here'),
'key' => ........
);
?>
you can use below to get only list array
<?php
foreach($arr as $key => $value)
{
if($key == 'list') {
$arr1=$value['list'];
break;
}
}
print_r($arr1);
?>
This question already has answers here:
How to extract specific array keys and values to another array?
(2 answers)
Closed 4 months ago.
I need help manipulating my two dimensional array. My array has many record sets with 2 columns of values and I'd like to manipulate the array so there is an array of many record sets with one column by converting one of my original columns as the key to the one column of values.
My Array:
[0]=>
[0]=> "48903"
[1]=> "SDFI"
[1]=>
[0]=> "2890"
[1]=> "DISL"
[2] =>
[0]=> "80890"
[1]=> "DISL"
...plus more
Intended array:
[0]=>
[48903]= "SDFI"
[2890]=>"DISL"
[80890] => "DISL"
...plus more
I've tried creating a new array with the intended keys and then unsetting the subarray but when the new array is vardumped at the end of script, it still shows that they subarray hasn't been removed.
my experimental codes
$newarr=array();
foreach($arr as $val => $rename){
$newarr[$rename[0]]= $rename;
}
foreach($newarr as $k => $v){
unset($v[0]); //does not remove/unset the extra column when newarr is var_dumped at the end of the script
$filter = array_filter($newarr, function($k) {
return $k == '1'; }); //or return $k !== 0; }) // other code to filter extra column that does not seem to work.
I think I came across a similar problem from someone else but they had 3 columns for each record set and wanted to reduce the number of columns to 2 and change the extra column as a key. However, I can't seem to locate that page. If anyone could find it and post a link, that would be great.
Any help would be great.. thank you in advance.
Try this:
<?php
// the function:
function arr2kv($arr) {
$res = array();
foreach($arr as $v) $res[$v[0]] = $v[1];
return $res;
}
// testing:
$n = array(
array("48903","SDFI"),
array("2890","DISL"),
array("80890","DISL")
);
print_r( arr2kv($n) );
/* // result:
Array
(
[48903] => SDFI
[2890] => DISL
[80890] => DISL
)
*/
Try this -
$newarr=array();
foreach($arr as $val => $rename){
$newarr[$rename[0]]= $rename[1];
}
I'm trying to receive an array via a cURL POST request, and I'm having an extrange issue.
Long story short: This is an api controller we're in, and when I json_encode a response...
echo json_encode($_POST['keys']); return;
The result (at the calling end of the api communication):
array(361) {
[0]=>
string(26) "some+urlencoded+string"
[1]=>
string(14) "and+some+other"
...
}
and so on. So the api receives my argument array no problem.
Then in the api I try a foreach loop to urldecode each string, to have those values in some other array:
$myArray = array();
foreach ($_POST['keys'] as $key => $value)
{
$myArray[$key] = urldecode($value);
// Or $myArray[] = urldecode($value); -- same result
}
echo json_encode($myArray); return;
And this is the result:
NULL
What am I doing wrong?
Thanks in advance :)
==================================================================================
EDIT: The problem seems to be that, in the api controller (that lives in a yii application) urledecode does not work. Neither does utf8_decode, nor base64_decode. At least they do not work inside a foreach loop, anyway. Why don't they work? Beats me. I'm still stuck.
==================================================================================
EDIT 2: I've made some progress in the isolation of the problem, asked another Q here at SO. Sorry for this, might as well be closed.
PHP (CI) cURL passed multidimensional array does not behave as one (Can't loop it)
I don't think your problem is here... are you sure your $_POST['keys'] is ok when you foreach it ? you should try to echo something in your loop, or print_r($_POST['keys']) just before.
I tried this :
$_POST['keys'] = Array('some+urlencoded+string','and+some+other') ;
$myArray = array();
foreach ($_POST['keys'] as $key => $value)
$myArray[$key] = urldecode($value);
echo '<pre>' ;
var_dump($_POST['keys']) ;
echo json_encode($_POST['keys']);
echo "\n" ;
echo json_encode($myArray);
echo '</pre>' ;
wich render this, looked pretty correct :
array(2) {
[0]=>
string(22) "some+urlencoded+string"
[1]=>
string(14) "and+some+other"
}
["some+urlencoded+string","and+some+other"]
["some urlencoded string","and some other"]
Make print_r on $_POST['keys'] and on $myArray, i think your loop is just not working.
This question already has answers here:
Array as session variable
(4 answers)
Closed 9 years ago.
I was wondering is it possible to have an associative array within a session array? If so, what would be the best way to do it and how can I loop through it? I have tried the following but it doesnt seem to work:
//The variables are post variables from a form
$_SESSION['users'][$id] = array('name'=>$name, 'status'=>$status, 'salary'=>"20000");
Here is how I am trying to loop through the session array:
foreach ($_SESSION['users'] as $id=>$value) {
echo $value;
}
Also, If I knew an id how can I get the name? Can I do $_SESSION['users']['1234']['name']?
Yes you can have an associative array within a session array. You can also loop through it with a for or a foreach loop. e.g.:
$array = $_SESSION['users'][$id];
foreach($array as $key => $value) {
var_dump($array[$key]); //Will dump info about a single element
}
However, it would be helpful to see your error message or additional details of what you are trying to do and what about it that isn't working.
EDIT
Based on your updated question, since you are accessing and array of arrays (theoretically) you would need to nest a foreach with another foreach to get at your values.
foreach($_SESSION['users'] as $arrays) {
foreach($arrays as $arrKey => $arrVal) {
var_dump($arrays[$arrKey]);
}
}
Running that on your data would output (with my own fake data to fill variables):
string(7) "johndoe"
string(6) "active"
string(5) "20000"
I am trying to add an array to an existing array. I am able to add the array using the array_push . The only problem is that when trying to add array that contains an array keys, it adds an extra array within the existing array.
It might be best if I show to you
foreach ($fields as $f)
{
if ($f == 'Thumbnail')
{
$thumnail = array('Thumbnail' => Assets::getProductThumbnail($row['id'] );
array_push($newrow, $thumnail);
}
else
{
$newrow[$f] = $row[$f];
}
}
The fields array above is part of an array that has been dynamically fed from an SQl query it is then fed into a new array called $newrow. However, to this $newrow array, I need to add the thumbnail array fields .
Below is the output ( using var_dump) from the above code. The only problem with the code is that I don't want to create a seperate array within the arrays. I just need it to be added to the array.
array(4) { ["Product ID"]=> string(7) "1007520"
["SKU"]=> string(5) "G1505"
["Name"]=> string(22) "150mm Oval Scale Ruler"
array(1) { ["Thumbnail"]=> string(77) "thumbnails/products/5036228.jpg" } }
I would really appreciate any advice.
All you really want is:
$newrow['Thumbnail'] = Assets::getProductThumbnail($row['id']);
You can use array_merge function
$newrow = array_merge($newrow, $thumnail);
Alternatively, you can also assign it directly to $newrow:
if ($f == 'Thumbnail')
$newrow[$f] = Assets::getProductThumbnail($row['id']);
else
...
Or if you want your code to be shorter:
foreach($fields as $f)
$newrow[$f] = ($f == 'Thumbnail')? Assets::getProductThumbnail($row['id']) : $row[$f];
But if you're getting paid by number of lines in your code, don't do this, stay on your code :) j/k