-3

I have a situation in PHP where I need to combine multiple array values and bind with the first array key, Let say I have following array,

[services] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 1
        )

    [package_type] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 1
        )

    [service_desc] => Array
        (
            [0] => Full HD
            [1] => Full HD
            [2] => Full HD
        )

    [service_price] => Array
        (
            [0] => 500
            [1] => 600
            [2] => 500
        )

Now , I want to bind all array with service type keys like services[0] will have the value of package_type[0], service_desc[0] and service_price[0]. The purpose is that I can easily identify all service related values with its Id. Can anyone suggest ?

2

1 Answer 1

0

array_map is key here. Leave the first argument as null and it will group as you want:

<?php

$data = 
[
    'services' =>
    [
        'programming',
        'debugging'
    ],
    'description' => 
    [
        'the process of writing computer programs.',
        'the process of identifying and removing errors from software/hardware'
    ]
];

$result = array_map(null, $data['services'], $data['description']);
var_export($result);

Output:

array (
  0 => 
  array (
    0 => 'programming',
    1 => 'the process of writing computer programs.',
  ),
  1 => 
  array (
    0 => 'debugging',
    1 => 'the process of identifying and removing errors from software/hardware',
  ),
)

Instead of writing out all your keys as arguments you could unpack like this:

array_map(null, ...array_values($data));

For something more elaborate, pass array_map a callable:

$keys   = array_keys($data);
$result = array_map(function(...$args) use ($keys) {
    return array_combine($keys, $args);
}, ...array_values($data));

var_export($result);

Output:

array (
  0 => 
  array (
    'services' => 'programming',
    'description' => 'the process of writing computer programs.',
  ),
  1 => 
  array (
    'services' => 'debugging',
    'description' => 'the process of identifying and removing errors from software/hardware',
  ),
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Let me try this.

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.