简体   繁体   中英

How to store array as key value pair in php

I have an array $result as follows

Array 
( [0] => Array ( 
[0] => Mr 
[1] => vinay 
[2] => hs 
[3] => tester 
[4] =>vinay.hs@abc.com 
[5] => 909099 
[6] => Yes ) 

[1] => Array ( 
[0] => Mr 
[1] => Suresh 
[2] => Kumar 
[3] => tester 
[4] => vinay.hs@abc.com 
[5] => 809090 
[6] => No ) 
).

I want to store this array as

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

[1] => Array ( 
[title] => Mr 
[firstname] => Suresh 
[lastname] => Kumar 
[job_title] => tester 
[email] => vinay.hs@abc.com 
[phone] => 809090 
[is_employed] => No ) ).

Explain me how to do this

$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.

$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;
}
$arr = array("title" => "Mr", "title" => "vinay", "key" => "value")

访问它:

$arr["title"]
array(
    array(
        'title' => 'Mr',
        'firstname' => 'vinay',
        'lastname' => 'hs',
        'job_title' => 'tester',
        'email' => 'vinay.hs@abc.com',
        'phone' => '909099',
        'is_employed' => TRUE
    ),
    array(
        'title' => 'Mr',
        'firstname' => 'Suresh',
        'lastname' => 'Kumar',
        'job_title' => 'tester',
        'email' => 'vinay.hs@abc.com',
        'phone' => '809090',
        'is_employed' => FALSE
    )
);

UPDATED:

My answer previously is dumb. If you are loading from CSV file, assuming the first element of array is the keys.

You might want to do something like this.

Sorry for my bad naming.

$keysArray = array_shift($arrayFromCSV);

$wantedArrayStructure = array();

foreach ($arrayFromCSV as $person) {
    $item = array();
    foreach ($person as $key => $value) {
        $item[$keysArray[$key]] = $value;
    }
    $wantedArrayStructure[] = $item;
}

var_dump($wantedArrayStructure);

If, is is result from msql query. You should using function to get the expected result:

mysql_fetch_assoc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM