Viewed   75 times

I have a multidimensional indexed array. Each element is an associative array with an id column which is unique between elements (its value never repeats within the array).

[indexed] =>Array
(
    [0] => Array
        (
            [id] => john
            [name] => John
            [age] => 29
        ),

    [1] => Array
        (
            [id] => peter
            [name] => Peter
            [age] => 30
        ),

    [2] => Array
        (
            [id] => harry
            [name] => Harry
            [age] => 19
        )
)

My goal is to convert this array into a multidimensional associative array, indexed by id values.

[indexed] =>Array
(
    [john] => Array
        (
            [id] => john
            [name] => John
            [age] => 29
        ),

    [peter] => Array
        (
            [id] => peter
            [name] => Peter
            [age] => 30
        ),

    [harry] => Array
        (
            [id] => harry
            [name] => Harry
            [age] => 19
        )
)

My best attempt so far is to loop over array elements and manually create the final array.

$associative = array();
foreach($indexed as $key=>$val) $associative[$val['id']] = $val;

I think it's not the most elegant solution. Is it possible to obtain the same result with built-in (more efficient) functions?

 Answers

3

The truth is php DOES offer a single, native function that allows you to replace the outer indexes with the values of a single column. The "magic" is in the 2nd parameter which tells php not to touch the subarray values when assigning the new keys.

Code: (Demo)

$indexed = [
    ['id' => 'john', 'name' => 'John', 'age' => 29],
    ['id' => 'peter', 'name' => 'Peter', 'age' => 30],
    ['id' => 'harry', 'name' => 'Harry', 'age' => 19],
];

var_export(array_column($indexed, null, 'id'));

Output:

array (
  'john' => 
  array (
    'id' => 'john',
    'name' => 'John',
    'age' => 29,
  ),
  'peter' => 
  array (
    'id' => 'peter',
    'name' => 'Peter',
    'age' => 30,
  ),
  'harry' => 
  array (
    'id' => 'harry',
    'name' => 'Harry',
    'age' => 19,
  ),
)
Monday, November 7, 2022
 
4

You need to iterate over your results, adding a new entry to the output when you encounter a new team, or updating the points value when you find the same team again. This is most easily done by initially indexing the output by the team name, and then using array_values to re-index the array numerically:

$teams = array();
foreach ($results as $result) {
    $team = $result['team'];
    if (!isset($teams[$team])) {
        $teams[$team] = array('team' => $team, 'points' => $result['punti']);
    }
    else {
        $teams[$team]['points'] += $result['punti'];
    }
}
$teams = array_values($teams);
print_r($teams);

Output (for your sample data):

Array
(
    [0] => Array
        (
            [team] => Red Bull Racing
            [points] => 418
        )
    [1] => Array
        (
            [team] => Scuderia Ferrari
            [points] => 353
        )
    [2] => Array
        (
            [team] => Mercedes-AMG
            [points] => 516
        )
    [3] => Array
        (
            [team] => Racing Point F1
            [points] => 147
        )
    [4] => Array
        (
            [team] => Haas F1
            [points] => 127
        )
)

Demo on 3v4l.org

Friday, August 12, 2022
 
5

Here is some code to handle what you had originally proposed as output.

/**
 * Give it and array, and an array of parents, it will decent into the
 * nested arrays and set the value.
 */
function set_nested_value(array &$arr, array $ancestors, $value) {
  $current = &$arr;
  foreach ($ancestors as $key) {

    // To handle the original input, if an item is not an array, 
    // replace it with an array with the value as the first item.
    if (!is_array($current)) {
      $current = array( $current);
    }

    if (!array_key_exists($key, $current)) {
      $current[$key] = array();
    }
    $current = &$current[$key];
  }

  $current = $value;
}


$education = array(
  'x[1]'     => 'Georgia Tech',
  'x[1][1]'  => 'Mechanical Engineering',
  'x[1][2]'  => 'Computer Science',
  'x[2]'     => 'Agnes Scott',
  'x[2][1]'  => 'Religious History',
  'x[2][2]'  => 'Women's Studies',
  'x[3]'     => 'Georgia State',
  'x[3][1]'  => 'Business Administration',
);

$neweducation = array();

foreach ($education as $path => $value) {
  $ancestors = explode('][', substr($path, 2, -1));
  set_nested_value($neweducation, $ancestors, $value);
}

Basically, split your array keys into a nice array of ancestor keys, then use a nice function to decent into the $neweducation array using those parents, and set the value.

If you want the output that you have updated your post to have, add this in the foreach loop after the line with 'explode'.

$ancestors[] = 0;
Thursday, December 22, 2022
 
colacx
 
5

You can make your existing code slightly more efficient (removes one function call per iteration, for one at the beginning:)

$b = array();
array_unshift($a, false);
while (false !== $key = next($a)) {
    $b[$key] = next($a);
}

Ok, (shudder) here's your one liner:

$b = call_user_func_array('array_merge', array_map(function($v) { return array($v[0] => $v[1]); }, array_chunk($a, 2)));
Monday, September 19, 2022
 
bam
 
bam
3

You can do it like this, do the calculation from the innermost of the array. Check the demo.

<?php
function f(&$array)
{
    foreach($array as $k => &$v)
    {
        if(is_array($v))
        {
            if(count($v) == count($v, 1))
            {
                unset($array[$k]);
                if($k == 'sum')
                {
                    $v =  array_sum($v);
                    $array[] = $v;

                }elseif($k == 'multiply'){
                    $v = array_product($v);
                    $array[] = $v;
                }else{

                    foreach($v as $vv)
                        $array[] = $vv;
                }
            }else
                f($v);
        }
    }
}

while(count($array) != count($array, 1))
{
    f($array);
}

print_r($array);

Note:

traverse array from outer to inner
traverse array from inner to outer

Monday, November 14, 2022
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :