Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store array as key value pair in php

Tags:

arrays

php

I have an array $result as follows

Array 
( [0] => Array ( 
[0] => Mr 
[1] => vinay 
[2] => hs 
[3] => tester 
[4] =>[email protected] 
[5] => 909099 
[6] => Yes ) 

[1] => Array ( 
[0] => Mr 
[1] => Suresh 
[2] => Kumar 
[3] => tester 
[4] => [email protected] 
[5] => 809090 
[6] => No ) 
).

I want to store this array as

Array
([0]=>Array ( 
[title] => Mr 
[firstname] => vinay 
[lastname] => hs 
[job_title] => tester 
[email] =>[email protected] 
[phone] => 909099 
[is_employed] => Yes ) 

[1] => Array ( 
[title] => Mr 
[firstname] => Suresh 
[lastname] => Kumar 
[job_title] => tester 
[email] => [email protected] 
[phone] => 809090 
[is_employed] => No ) ).

Explain me how to do this

like image 469
n92 Avatar asked Apr 12 '11 03:04

n92


People also ask

How do you create an array of key value pairs in PHP?

Creating a Numeric Array If you create an array with [] or array() by specifying only a list of values instead of key/value pairs, the PHP engine automatically assigns a numeric key to each value. The keys start at 0 and increase by one for each element.

How do you create a key value pair array?

We are required to write a JavaScript function that takes in one such array and constructs an object where name value is the key and the score value is their value. Use the Array. prototype. reduce() method to construct an object from the array.


2 Answers

$fp = fopen('foo.csv', 'r');
$fields = fgetcsv($fp); // assumes fields are the first row in the file

// or $fields =  array('title', 'firstname', 'lastname', 'job_title', 'email', 'phone', 'is_employed');

$records = array();
while ($record = fgetcsv($fp))
{
  $records[] = array_combine($fields, $record);
}

Obviously it needs error handling added to it.

like image 142
Matthew Avatar answered Sep 22 '22 08:09

Matthew


$newarray=array();

foreach($result as $res) {
 $a = array();
 $i = 0;
 foreach(array('title','firstname','lastname','job_title','email','phone','is_employed') as $key) {
  $a[$key] = $res[$i++];
 }
 $newarray[] = $a;
}
like image 20
Raisen Avatar answered Sep 19 '22 08:09

Raisen