Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

php iterate over an array made up of strings, instead of objects

I need to iterating over an array made up of strings, not objects. I've tried hunting and implementing other stackoverflow answers but dont seem to be able to make this work.

The array:

var_dump(`$myids`);
array(3) {
  [0]=>
  string(2) "45"
  [1]=>
  string(2) "46"
  [2]=>
  string(2) "47"
}

I tried:

$myids=$_POST['myids'];
foreach ($myids as $value){
$value['myids'];
}

Gives the error - Illegal string offset 'myids'.

Then I tried:

$myids=$_POST['myids'];
foreach ($myids as $value){
$value->myids;
}

Gives the error - Trying to access proprieties of a non object.

So I thought maybe adding the key to the foreach but that wasnt the solution. At the risk of sounding dumb, what is the solution to access each value of the array?

question from:https://stackoverflow.com/questions/65911183/php-iterate-over-an-array-made-up-of-strings-instead-of-objects

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, there is no "myids" key in the array. You are using purely numeric IDs, so none of the keys will be named in your array.


$myids=$_POST['myids'];
foreach ($myids as $value){
    echo $value;
}

This is unrolling each row of $myids into $value. Once it unrolls and enters the loop, you should not try to access $myids, but should work solely with $value, which represents ONLY the current row.

On the first iteration, $value will contain: string(2) "45"

On the second iteration, $value will contain: string(2) "46"

Third iteration: string(2) "47"

As you can see, $value only ever contains string values, so there are no arrays or keys to access within. It's pulling one row on each iteration of the loop and inserting it directly into $value. As such, you only need to echo $value directly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...