0

So i tried a lot of possible codes out but i can't seem to find a proper solution.

First let's start with the the wished array (i will show it in a json format as it's easier to read)

{
    "transaction": {
        "input": [
            {
                "address": "a",
                "value": 4294967295
            },
            {
                "address": "b",
                "value": 51515
            }
        ],
        "output": [
            {
                "address": "aa",
                "value": 551
            },
            {
                "address": "bb",
                "value": 66564
            }
        ]
    }
}

I'm using 2 foreach loops to get data that i wanna put in inputs & outputs

Here's the code im using:

//Get Output Addresses & Value
$tmp_array = array();
foreach($json['result']['vout'] as $a)
{
    $value = $a['value'];
    $address = $a['scriptPubKey']['addresses'][0];
    
    $tmp_array = array('wallet' => $address, 'value' => $value);
    $input = array_merge($input, $tmp_array);


};

$input = array('inputs' => $tmp_array);
$input = json_encode($input);
print_r($input);

That's the code for me getting the data and trying to put it into the array. Now i have a problem, it only adds data from the last iteration of the loop. I'm trying to get a code that gets it in a strucuture like above. Whatever solution gets sent, it should be applicable so i can paste the same code in the other loop that is for the outputs

1 Answer 1

1

You are assigning the $input variable after the loop with the value of $tmp_array which will be the value from the last iteration, as you described. To fix this you should initialize the $input array as empty array at the beginning and merge that with the new data:

//Get Output Addresses & Value
$inputs = array();
foreach($json['result']['vout'] as $a)
{
    $value = $a['value'];
    $address = $a['scriptPubKey']['addresses'][0];
    
    $tmp_array = array('wallet' => $address, 'value' => $value);
    $inputs[] = $tmp_array; // push to array
};

$input = json_encode(array('inputs' => $inputs));
print_r($input);
Sign up to request clarification or add additional context in comments.

3 Comments

This gives out an empty array: {"inputs":[]}
Of course! I made a mistake, will edit it.
@SamUncle no problem! If this solved your problem, could you please mark the answer as such? Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.