2013-04-30 4 views
0

J'ai un tableau qui contient plusieurs tableaux. J'essaie de changer la clé qui est ["517f467ca2ec9"] ["517f467ca310c"] ... mais supposons que je ne sais pas sur le texte de la clé de tableau, j'utilise l'extrait ci-dessous qui m'a donné une erreur Undefined offset: 1Modifier les clés de tableau dans un tableau multidimensionnel PHP

array(74) { 
    [0]=> 
    array(9) { 
    ["517f467ca2ec9"]=> 
    string(0) "" 
    ["517f467ca310c"]=> 
    string(0) "" 
    ["517f467ca321a"]=> 
    string(0) "" 
    ["517f467ca3320"]=> 
    string(0) "" 
    ["517f467ca3427"]=> 
    string(0) "" 
    ["517f467ca352a"]=> 
    string(0) "" 
    ["517f467ca3666"]=> 
    string(0) "" 
    ["517f467ca378d"]=> 
    string(0) "" 
    ["517f467ca3897"]=> 
    string(0) "" 
    } 
    [1]=> 
    array(9) { 
    ["517f467ca2ec9"]=> 
    string(0) "" 
    ["517f467ca310c"]=> 
    string(0) "" 
    ["517f467ca321a"]=> 
    string(0) "" 
    ["517f467ca3320"]=> 
    string(0) "" 
    ["517f467ca3427"]=> 
    string(0) "" 
    ["517f467ca352a"]=> 
    string(0) "" 
    ["517f467ca3666"]=> 
    string(0) "" 
    ["517f467ca378d"]=> 
    string(0) "" 
    ["517f467ca3897"]=> 
    string(0) "" 
    } 

php extrait

foreach ($rows as $k=>$v){ 
    $rows[$k] ['running_days'] = $rows[$k] [0]; 
    unset($rows[$k][0]); 
} 
+2

Et la question est? – zerkms

+0

comment puis-je changer la clé dans mon cas? –

+0

Que signifie "changer la clé"? – zerkms

Répondre

2

S'il vous plaît essayer ce code, il vous aidera à

function changeKey(&$data) 
{ 
    foreach ($data as $key => $value) 
    { 
    // Convert key 
    $newKey = 'any'; // new key goes here 

    // Change key if needed 
    if ($newKey != $key) 
    { 
     unset($data[$key]); 
     $data[$newKey] = $value; 
    } 

    // Handle nested arrays 
    if (is_array($value)) 
    { 
     changeKey($data[$key]); 
    } 
    } 
} 

$test = array('foo' => 'bar', 'moreFoo' => array('more' => 'foo')); 
changeKey($test); 
print_r($test); 
0
$rows[$k]['running_days'] = array_shift($rows[$k]); 
1

Il semble que vous ayez un tableau multidimensionnel. Vous pouvez essayer celui-ci ...

// array container 
$records = 'Your array with key here'; 

// init new array container 
$myarray = array(); 

foreach ($records as $items) { 
    foreach ($items as $k => $v) { 
     $myarray[$k]['running_days'] = $v; 
    } 
} 

printr_r($myarray); 
Questions connexes