Combine arrays within array

0

Someone can help me, please.

I have an array in this style:

$arrayTable = array(
   0 => array(
      'idApiUm' => 123,
      'title'  => 'Teste'
   ),
   1 => array (
      'idApiDois' => 765,
      'title'  => 'Título'
   ),
   2 => array(
      'idApiUm' => 632,
      'title'  => 'Nome'
   ),
   3 => array(
      'idApiDois' => 999,
      'title'  => 'Teste'
   ),
);

You need to merge all arrays inside it that have the same value in 'title', and leave the key like this:

0 => array(
   'idApiUm' => 123,
   'idApiDois' => 999,
   'title'   => 'Teste'
),

Is it possible? I can not solve this problem ...

    
asked by anonymous 27.12.2018 / 17:45

2 answers

1

First look for the keys that are repeated in the case that is title , then their numeric indexes of array with the data and then add them with #

<?php

$arrayTable = array(
   0 => array(
      'idApiUm' => 123,
      'title'  => 'Teste'
   ),
   1 => array (
      'idApiDois' => 765,
      'title'  => 'Título'
   ),
   2 => array(
      'idApiUm' => 632,
      'title'  => 'Nome'
   ),
   3 => array(
      'idApiDois' => 999,
      'title'  => 'Teste'
   ),
);

function get_items($array, $field)
{
    return array_unique(array_map(function($value) use ($field) { 
            return $value[$field]; 
        }, $array)
    );
}

function get_index($array, $field, $search) {
    return array_keys(
            array_filter($array,
                    function ($value) use ($search, $field) {
                        return (strpos($value[$field], $search) !== false);
                    }
            )
    );
}


$array_new = array();
foreach (get_items($arrayTable, 'title') as $value) 
{
    $array_index = get_index($arrayTable, 'title', $value);
    $array_index_item = array();
    foreach ($array_index as $i) 
    {
        if (count($array_index_item) == 0)
        {
            $array_index_item = $arrayTable[$i];
        }
        else
        {
            $array_index_item = array_merge($array_index_item, $arrayTable[$i]);
        }
    }
    $array_new[] = $array_index_item;
}

var_dump($array_new);

Example: IDEONE

>

27.12.2018 / 19:38
1

Try this ...

<?php  $arrayTable = array(
    0 => array(
        'idApiUm' => 123,
        'title' => 'Teste'
    ),
    1 => array (
        'idApiDois' => 765,
        'title' => 'Título'
    ),
    2 => array(
        'idApiUm' => 632,
        'title' => 'Nome'
    ),
    3 => array(
        'idApiDois' => 999,
        'title' => 'Teste'
    ),
);

$result = array();

function test_print($item, $key)
{
    global $result;
    if(is_string($key))
        $result[$key] = $item;
    else
        $result[$key] += $item;
}

foreach ($arrayTable as $x)
    if($x['title'] == 'Teste')
       array_walk($x, 'test_print');
print_r($result);
?>

Array ([idApiUm] => 123 [title] => Test [idApiDois] = > 999)

    
27.12.2018 / 18:46