在foreach中更改密钥名称

时间:2015-07-22 10:37:03

标签: php arrays foreach

我想要编辑一个数组键名,将它从日期更改为数字顺序ID,并将日期输入数组。

  [entries] => Array
        (
            [2015-07-19] => Array
                (
                    [value] => 14.8
                )

            [2015-07-18] => Array
                (
                    [value] => 14.9
                )

  [entries] => Array
        (
            [0] => Array
                (
                    [value] => 14.8
                    [date] => 2015-07-19
                )

            [1] => Array
                (
                    [value] => 14.9
                    [date] => 2015-07-18
                )

2 个答案:

答案 0 :(得分:0)

你试过了吗?

$entries = array(
     '2015-07-19' => array(
          'value' => 14.8
     ),
     '2015-07-18' => array(
          'value' => 14.9
     )
);
$result = array();
foreach ($entries as $key => $value) {
     $result['entries'][] = array('date'=> $key, 'value' => $value['value']);
}
print_r($result);

答案 1 :(得分:0)

我的建议(没有创建新数组):

$entries = array(
    '2015-07-19' => array ('value' => 14.8),
    '2015-07-18' => array ('value' => 14.9),        
);

foreach ($entries as $key => &$entry) 
{
    $entry['date'] = $key;
}
unset($entry);

$entries = array_values($entries);