wichtel
wichtel

Reputation: 191

PHP access array element

At the moment I stuck on how to get access to the element. Structure of array is like this:

{
"network":"BTC",
"event_type":"address-transactions",
 "addresses":{
  "3PvGLecQQMnm8oB2EqLbV94LFh7FLZpgJv":0
 },
"data":{},
"retry_count":0
}

How to get the value "3PvGLecQQMnm8oB2EqLbV94LFh7FLZpgJv". As you might already guess this is for some kind of callback. I'm totally confused on how to access the value since the lib of payment provider only returns the callback as an array.

When I use:

$payload['addresses'][0]

It says undefined index, using

dd($payload['addresses']);

returns:

array:1 [
"3PvGLecQQMnm8oB2EqLbV94LFh7FLZpgJv" => 0
]

Upvotes: 0

Views: 70

Answers (2)

Elbarto
Elbarto

Reputation: 1253

When it comes to json, you can access your data as an array with json_decode() : http://php.net/manual/fr/function.json-decode.php

The 2nd parameter is a boolean : When TRUE, returned objects will be converted into associative arrays.

$json = '{
    "network":"BTC",
"event_type":"address-transactions",
 "addresses":{
        "3PvGLecQQMnm8oB2EqLbV94LFh7FLZpgJv":0
 },
"data":{
    },
"retry_count":0
}';

$test = json_decode($json, true);

Then :

foreach ($test["addresses"] as $key => $value) {
   echo sprintf("key: %s, value %s", $key, $value);
}

Upvotes: 2

Sahil Gulati
Sahil Gulati

Reputation: 15141

PHP code demo

You can access a array value with some index defined to it, here

3PvGLecQQMnm8oB2EqLbV94LFh7FLZpgJv => key

0 => value

and 3PvGLecQQMnm8oB2EqLbV94LFh7FLZpgJv is the key which you want to find.

$string = '{
     "network":"BTC",
     "event_type":"address-transactions",
     "addresses":{
       "3PvGLecQQMnm8oB2EqLbV94LFh7FLZpgJv":0
     },
     "data":{},
     "retry_count":0
 }';
$array = json_decode($string, true);
echo key($array["addresses"]);

Upvotes: 1

Related Questions