1

I have below array

  $a = [
    [
      0 => 'Name',
      1 => 'Address '
    ],
    [
      0 => 'Name 1',
      1 => 'Address 1'
    ],
    [
      0 => 'Name 2',
      1 => 'Address 2'
    ]
  ];

How to assign 1st element value to rest of the keys?

So it becomes

  $a = [
    [
      'Name' => 'Name 1',
      'Address' => 'Address 1'
    ],
    [
      'Name' => 'Name 2',
      'Address' => 'Address 2'
    ]
  ];

So basically I am getting this array of excel file & need above kind of array result.

0

2 Answers 2

5

use array_shift() with foreach() and array_combine():

$firstValue = array_shift($a); //remove first value from array and assign it to variable

foreach($a as &$v){ //loop over remaining values
    $v = array_combine($firstValue,$v); //combine both array to create key value pair
}

print_r($a);

Output: https://3v4l.org/1J6pU And https://3v4l.org/qMFPi

Reference:- Passing by Reference

Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

$array = [
    [
      0 => 'Name',
      1 => 'Address '
    ],
    [
      0 => 'Name 1',
      1 => 'Address 1'
    ],
    [
      0 => 'Name 2',
      1 => 'Address 2'
    ]
  ];
$new_array = array();
$name = $array[0][0];
$address = $array[0][1];
//remove first key
array_shift($array);
foreach($array as $key => $value)
{
    $new_array[$key] = [
       $name => $value[0],
       $address => $value[1]
    ];
}

var_dump($new_array);

Output:

array(2) {
  [0]=>
  array(2) {
    ["Name"]=>
    string(6) "Name 1"
    ["Address "]=>
    string(9) "Address 1"
  }
  [1]=>
  array(2) {
    ["Name"]=>
    string(6) "Name 2"
    ["Address "]=>
    string(9) "Address 2"
  }
}

1 Comment

Thanks for answer. It is working fine, but Per Array I have 50 values so each contains 0-49

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.