1

I have Laravel 6 code below displays the array with the object format. So I like to display instead of object-based array, just array as I have mentioned below.

 $ins_affiliations =   DB::table('ins_affiliations as af')
                ->select('af.id','af.name')               
                ->where(['af.ins_category_id' => $ins_category_type[0]->category_id])
                ->get()->toArray(); 

my code shows

  Array
(
    [0] => stdClass Object
        (
            [id] => 12
            [name] => NSDC
        )

    [1] => stdClass Object
        (
            [id] => 13
            [name] => NCVT
        )

    [2] => stdClass Object
        (
            [id] => 14
            [name] => AICTE
        )

    [3] => stdClass Object
        (
            [id] => 15
            [name] => Others
        )

)

what I need

Array
(    
    [12] => NSDC
    [5] => NCVT
    [8] => AICTE
    [11] => Others   
)

How can I achieve this?

3
  • You need json_decode Commented Oct 28, 2020 at 17:50
  • 3
    You can use pluck('name', 'id') instead get() to execute your query Commented Oct 28, 2020 at 17:51
  • @sta json_decode does not work as I expected Commented Oct 28, 2020 at 17:55

1 Answer 1

1

You can remove ->toArray() when you retrieve data and then use mapWithKeys which is collection method

$ins_affiliations->mapWithKeys(function ($item) { return [$item->id => $item->name]; })

Then you can use ->all() if you want to get plain array

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

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.