1

I want to make array without foreach loop. This is should be returned:

array:4 [
  0 => array:1 [
    "name" => "tag1"
  ]
  1 => array:1 [
    "name" => "tag2"
  ]
  2 => array:1 [
    "name" => "tag3"
  ]
  3 => array:1 [
    "name" => "tag4"
  ]
]

I made it to work like this:

$tags=[];
$j=0;
foreach($woo->tags as $tag){
    $tags[$j]['name']=$tag;
    $j++;
}

But when I have a lot of tags it can be slow in foreach loop. My tags are saved in database in text field like tag1,tag2,tag3,tag4 enter image description here

Is there any other faster way to return this..

0

1 Answer 1

1

Try array_map, I haven't actually benchmarked the both but it is one of (if not your only) alternative:

$tags = array_map(function($tag) {
    return ['name' => $tag];
}, $woo->tags);

For what it's worth, if you are actually storing so many tags in a singular column that it actually slows PHP down, might be something you need to step back and think about improving.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.