PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 29, 2022

[FIXED] Get array result with id in key instead of 0,1 in array key

 January 29, 2022     codeigniter, mysql, php     No comments   

Issue

I have used below query to get array result with id as key value,

$this->db->select('gp.id, gp.lot_no, SUM(gb.weight) AS weight, SUM(gb.staple) AS staple, SUM(gb.mic) AS mic, SUM(gb.strength) AS strength, SUM(gb.trash) AS trash, gb.color_grade');
            $this->db->from(GIN_BALES . ' gb');
            $this->db->join(GIN_PROCESS . ' gp', 'gp.id=gb.process_id'); 
            $this->db->where('gb.sold_status', 0);
            $this->db->where('gp.ginner_id', $this->prscr_id);
            $this->db->where('gp.program', $program_id);
            $this->db->group_by('gp.id');
            $lot_details = $this->db->get()->result();

But I getting the array result like below and array key have 0,1.I want that array key with id like,561,562.

Array
(
    [0] => stdClass Object
        (
            [id] => 561
            [lot_no] => 1
            [weight] => 16230
            [staple] => 3600
            [mic] => 0
            [strength] => 0
            [trash] => 0
            [color_grade] => 0
        )

    [1] => stdClass Object
        (
            [id] => 562
            [lot_no] => 2
            [weight] => 15523
            [staple] => 3600
            [mic] => 0
            [strength] => 0
            [trash] => 0
            [color_grade] => 0
        )
)

Can anyone provide solution for this query issue?


Solution

Here is one liner,

// null will take id as key and whole array as value
$temp = array_column($temp, null, "id");

Reference: array_column.

Demo.

Output:

Array
(
    [561] => stdClass Object
        (
            [id] => 561
            [lot_no] => 1
            [weight] => 16230
            [staple] => 3600
            [mic] => 0
            [strength] => 0
            [trash] => 0
            [color_grade] => 0
        )

    [562] => stdClass Object
        (
            [id] => 562
            [lot_no] => 2
            [weight] => 15523
            [staple] => 3600
            [mic] => 0
            [strength] => 0
            [trash] => 0
            [color_grade] => 0
        )

)


Answered By - Rahul
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing