Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

cookie_good's avatar

PHP 101 question

So I've got this mess.

        (
            [product_code] => "1234"
            [0] => {"manufacturer_alias":"Kwickie Mart","manufacturer_code":"ABC","product_code":"1234"}
        )

The goal is to insert json into a MySQL 5.6 table. This version of MySQL predates all the cool JSON functions SQL sometimes has.

[product_code] sometimes has multiple json values. By that I mean, there could be a [product_code] => "1234" with [0] => {something completely different but with the same keys}

Is there an easy way to aggregate these json values?

Failing that, is there an easy way to format the output of an array so that it can be sucked into a Laravel Database Seeder?

Many thanks in advance.

0 likes
4 replies
jlrdw's avatar

See json_decode in PHP manual.

Will probably need to loop over data and do whatever you need to with it after decoded.

fylzero's avatar

What's with the parens around this? Is this supposed to be an object an array?

23 likes
cookie_good's avatar

fylzero

It is copy and paste from the output of print_r

jldrw

I actually ran json_encode to create that result. Maybe I haven't posed the question clearly. Basically, I want json, but I need to append values in my array, so that [product_code] is unique throughout the array, when product_code repeats, and there are different json values associated with it, the values will aggregate, like this.

[0] => [{first json bs}, {second json bs}, {third json bs}]

cookie_good's avatar

So here's my solution. PS I'm not going to tag myself as best answer so please chime in if you guys know a better way.

>>>DB::statement("
create table blah_blah_blah                                        
    (id int(11),                                                                     
    product_code varchar(255),                                                     
    json_bs text)                                                                      
");

then also in tinker

>>>for($i = 0; $i < count($json_bs); $i++){                                       
    DB::table('blah_blah_blah')->insert(array('id' => $i, 'product_code' => $json_bs[$i]['product_code'], 'json_bs' => $json_bs[$i][0]));                                    
}

Now I have a table in SQL and I'm going to use data manipulation language to sort this mess.

I'm sure there is a better way to do this, but I don't know it.

edited later... here's the magic SQL. Hope it helps someone.

mysql> create table very_blah 
                    select 
                        product_code, 
                        group_concat(distinct json_bs separator ', ') as json_bs 
                    from blah_blah_blah 
group by product_code;

Please or to participate in this conversation.