Home > Blockchain >  Turn an array format string into actual Array on PHP
Turn an array format string into actual Array on PHP

Time:03-11

I am struggling to find the solution for converting string type array into actual array. I have a database column where it stores plain-text exactly like below :

array ( 'mc_gross' => '100.00', 'auth_exp' => '18:35:24 Apr 08, 2022 PDT',  
 'protection_eligibility' => 'Eligible', 'payer_id' => 'J4RS8Q76ZEKZ2', 'payment_date' =>                        '17:35:24 Mar 10, 2022 PST', 'payment_status' => 'Pending', 'charset' => 'UTF-8',  
 'first_name' => 'John', 'transaction_entity' => 'auth', 'quantity' => '4',) 

I need to access 'quantity' value from this column. I have tried to fetch database and then tried to access it through the code below:

while($resp=$db->fetch($response)){
                foreach ($resp as $key => $value) {
                    $gateway[] = $resp[$key];
                    }
                }
            }
        echo $gateway[0]['quantity'];

I am getting 'a' after this command. it is the first character of string as you see.

The output of echo $gateway[0] is :

array ( 'mc_gross' => '100.00', 'auth_exp' => '18:35:24 Apr 08, 2022 PDT',  
 'protection_eligibility' => 'Eligible', 'payer_id' => 'J4RS8Q76ZEKZ2', 'payment_date' =>                        '17:35:24 Mar 10, 2022 PST', 'payment_status' => 'Pending', 'charset' => 'UTF-8',  
 'first_name' => 'John', 'transaction_entity' => 'auth', 'quantity' => '4',) 

I have tried to access by : $gateway[0][1] (just for example) but this only shows me : a

As you see it is saved as string, I don't know how to handle this. Any help would be highly appreciated.

CodePudding user response:

[
    'mc_gross' => '100.00',
    'auth_exp' => '18:35:24 Apr 08, 2022 PDT',
    'protection_eligibility' => 'Eligible',
    'payer_id' => 'J4RS8Q76ZEKZ2',
    'payment_date' => '17:35:24 Mar 10, 2022 PST',
    'payment_status' => 'Pending',
    'charset' => 'UTF-8',
    'first_name' => 'John',
    'transaction_entity' => 'auth',
    'quantity' => '4',
] // this is $gateway[0]

Simply use:

$gateway[0]['quantity']

to get the quantity value

CodePudding user response:

The 'string type arrays' are so-called associative arrays.

The result of $gateway[0] is such an associative array. More precise your array $gateway contains another associative array at its first index [0]. Therefore using

 $gateway[0]['quantity']

would be your way to go.


As a bonus tip you should check the array documentation of php: https://www.php.net/manual/en/language.types.array.php

  •  Tags:  
  • php
  • Related