开发者

How to build dynamically an array - add values in loop

开发者 https://www.devze.com 2023-02-15 19:24 出处:网络
A question from PHP se开发者_如何学运维lf-learner. My question is how can one dynamically build an array.

A question from PHP se开发者_如何学运维lf-learner.

My question is how can one dynamically build an array.

I have an array of some class values

$tags;

a class tag has a field called Text;

I need to build an array of strings populated from that field

NOTE for downvoters. I am not PHP developer. I just need to do one simple task. I just do not know how to dynamically build an array of strings. That is my question. Hope this question will help other people who are learning PHP.


$textArray = array();

foreach($tags as $tag)
{
    $textArray[] = $tag->Text;
}

This will take each tag object in the $tags array and add the Text value to an array called $textArray.

If this isn't what you were looking for, please let me know and I will do my best to adapt my answer.


class Tag {
    public $Text;
}

$tag1 = new Tag();
$tag2 = new Tag();
$tags = Array($tag1, $tag2);

Is that your problem? If so, keep in mind that PHP has loose data types so $Text could very well be a string. Try something like this:

$NewTags = Array();
foreach($Tags as $tag) {
    $NewTags[] = $tag->Text;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消