0

I am doing laravel project. I have one sql query as,

$catcount=2;
    for($i=0;$i<$catcount;$i++) {
        $subCat[] = Category::where('parent_id', '=', $userCategory[$i])->pluck('id');
    }

$subCat returns an array as,

[[54,55,56,57,58],[48,49,50,51,52]]

I want this array as a single dimensional array like,

[54,55,56,57,58,48,49,50,51,52]

I am not getting how to do this, Please help and thanks in advance.

3
  • array_merge($subCat[0],$subCat[1]) Commented Apr 6, 2016 at 10:22
  • what if count is more than 2 Commented Apr 6, 2016 at 11:05
  • in that case, check my answer Commented Apr 6, 2016 at 11:18

5 Answers 5

1

I suggest You to do ids merge before querying, so You will save some run time by accessing database only one time.

$catcount    = 2;
$parents_ids = [];
for ($i = 0; $i < $catcount; $i++) {
    $parents_ids[] = $userCategory[$i];
}
$subCats = Category::whereIn('parent_id', $parents_ids)->pluck('id');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I got what I exactly wanted :)
0
$catcount=2;
for($i=0;$i<$catcount;$i++) {
   $subCat[] = Category::where('parent_id', '=' $userCategory[$i])->pluck('id');
}

array_merge($subCat[0],$subCat[1]);

1 Comment

Thanks for reply but what if I got count as 3 or 4,etc
0

From your final array, you can just do an array merge

list($a1, $a2) = $subCat;
$subCat = array_merge($a1, $a2);

Comments

0

There are a lot of ways to do that. One of them: simple, but universal, readable and updatable (if something will change in your data structure, you'll be able to update this code in no time):

$newArr = [];
foreach ($subCat as $subArr) {
    foreach ($subArr as $value) {
        $newArr[] = $value;
    }
}

Comments

0

if your array have multiple elements, you can merge them using this code:

$subCats = call_user_func_array("array_merge", $subCat);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.