A
A
Alexander Sevirinov2018-06-02 11:48:55
PHP
Alexander Sevirinov, 2018-06-02 11:48:55

How to iterate over an array and bring it to the required form?

There is an array in the input:

Array
(
    [project_id] => 4
    [user_id_1190647361] => 1190647361
    [user_id_1977462916] => 1977462916
    [user_id_169505052] => 169505052
    [user_id_622870866] => 622870866
    [user_id_1436905292] => 1436905292
    [user_id_2720806559] => 2720806559
)

It is required to iterate over the array and bring it to the required form:
Array
(
    [0] => Array
        (
            [project_id] => 4
            [user_id] => 1190647361
        )
    [1] => Array
        (
            [project_id] => 4
            [user_id] => 1977462916
        )
    [2] => Array
        (
            [project_id] => 4
            [user_id] => 169505052
        )
    [3] => Array
        (
            [project_id] => 4
            [user_id] => 622870866
        )
    [4] => Array
        (
            [project_id] => 4
            [user_id] => 1436905292
        )
    [5] => Array
        (
            [project_id] => 4
            [user_id] => 2720806559
        )
)

Help please, the plug has happened, I've been stupid for an hour.
I write like this:
$i = 0;
foreach ($post_data as $key => $item)
{
  if ($key === 'project_id')
  {
    $data[$i][$key] = $item;
  } else
  {
    $data[$i]['user_id'] = $item;
  }
  $i++;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Samsonov, 2018-06-02
@sevirinov

$data = [];
$projectId = isset($post_data['project_id']) ? $post_data['project_id'] : null;
foreach ($post_data as $key => $value) {
    if ($key == 'project_id') {
        continue;
    }

    $data[] = [
        'project_id' => $projectId,
        'user_id' => $value
    ];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question