Search code examples
phpcodeigniter

how to add json serilize data into the database using php


This is my array and i want to convert this as json and added to the database

Array(

[0] => Array

    (

        [id] => e4da3b7fbbce2345d7772b0674a318d5

        [channel] => Array
            (

                [0] => 1
                [1] => 2
            )

    )
)

I want to store data like this where id remain same and channel will add to the next json bracket with same id

[{"id":"e4da3b7fbbce2345d7772b0674a318d5","channel":1},{"id":"e4da3b7fbbce2345d7772b0674a318d5","channel":2}]

Code

    $var1 = array([
                        'id' => $hash_user,
                        'channel' => $channel
                    ]);
                //  print_r($var1);
                    
                    foreach($var1 as $id){
                    
                        
                        $encode_data = $id['id'] . $id['channel'][0].  $id['id'] .  $id['channel'][1];
                        
                        $see = json_encode($encode_data);
                
                    
                    }
                    
                    print_r($see);
                    
                    print_r($encode_data);
                    //
                    die;
                    $info['user_hash'] = $encode_data;
                    
                        
            

Solution

  • You should be clear in your post. But given the information, I assume you need to change the array you have to that JSON.

    What you have:

    $databaseArray = [[ "id" => "e4da3b7fbbce2345d7772b0674a318d5", "channel" => [1,2]]];
    $json = json_encode($databaseArray);
    

    What you want:

    $databaseArray = [[ "id" => "e4da3b7fbbce2345d7772b0674a318d5", "channel" => 1]];
    $json = json_encode($databaseArray);
    

    What you need to change:

    $databaseArray = [
        [ "id" => "e4da3b7fbbce2345d7772b0674a318d5", "channel" => [1,2]],
        [ "id" => "1235437fbbce2345d7772b0674a32342", "channel" => [1,2]]
    ];
    $databaseMergedArray = [];
         // You need to set the channel to a value instead of array. 
         foreach($databaseArray as $key => $item) {
             foreach($databaseArray[$key]["channel"] as $channel) {
                 $item["channel"] = $channel;
                 $databaseMergedArray[] = $item;
             }
         }
    
    $json = json_encode($databaseMergedArray);
    echo ($json);