0

I am using codeigniter php programming and I have 3 arrays like

array(1) {
[1506546000]=>
object(stdClass)#34 (1) {
["purchases"]=>int(120)
}
}
array(1) {
[1506546000]=>
object(stdClass)#32 (1) {
["exchange_items"]=>int(10)
}
}
array(3) {
[1506546000]=>
object(stdClass)#40 (1) {
["production_system"]=>int(16050)
}
[1506373200]=>
object(stdClass)#33 (1) {
["production_system"]=>int(2250)
}
[1506805200]=>
object(stdClass)#39 (1) {
["production_system"]=>int(150)
}
}

I need to merge them in one array with the key to be like this

array(1) {
[1506546000]=>
["purchases"]=>int(120)
["exchange_items"]=>int(10)
["production_system"]=>int(16050)
}
array(1) {
[1506373200]=>
["purchases"]=>null
["exchange_items"]=>null
["production_system"]=>int(2250)
}
array(1) {
[1506373200]=>
["purchases"]=>null
["exchange_items"]=>null
["production_system"]=>int(150)
}

I used array_merge_recursive() but it doesn't give me exactly what I need, So any help to do that?

1
  • Where are these payloads coming from? Do you know all of the column names in advance? Commented Jul 31, 2024 at 5:46

1 Answer 1

1

I don't think there's a PHP built in function that's going to do what you want to do, but I could be wrong. You could just do this:

<?php

$final_arr = array();

function setup()
{
    return array(
        'purchases'         => NULL,
        'exchange_items'    => NULL,
        'production_system' => NULL
    );
}

$arr1 = array(
    1506546000 => (object) array(
        'purchases' => 120
    )
);

$arr2 = array(
    1506546000 => (object) array(
        'exchange_items' => 10
    )
);

$arr3 = array(
    1506546000 => (object) array(
        'production_system' => 16050
    ),
    1506373200 => (object) array(
        'production_system' => 2250
    ),
    1506805200 => (object) array(
        'production_system' => 150
    )
);

foreach( array( $arr1, $arr2, $arr3 ) as $array )
{
    foreach( $array as $k => $v )
    {
        if( ! array_key_exists( $k, $final_arr ) )
            $final_arr[$k] = setup();

        foreach($v as $k2 => $v2)
        {
            $final_arr[$k][$k2] = $v2;
        }
    }
}

echo '<pre>';
print_r( $final_arr );
echo '</pre>';
Sign up to request clarification or add additional context in comments.

Comments

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.