0

I have an array that has multiple arrays inside. I am trying to change of the key which is ["517f467ca2ec9"] ["517f467ca310c"]... however assume that i don't know about the array key text, I am using the snippet below which gave me an error Undefined offset: 1

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 snippet

foreach ($rows as $k=>$v){
   $rows[$k] ['running_days'] = $rows[$k] [0];
   unset($rows[$k][0]);
}
5
  • how do i actually change the key in my case? Commented Apr 30, 2013 at 4:35
  • what does "change the key" mean? Commented Apr 30, 2013 at 4:37
  • I am trying to change of the key which is ["517f467ca2ec9"] ["517f467ca310c"]... Commented Apr 30, 2013 at 4:39
  • and what do you want to change them TO? Commented Apr 30, 2013 at 4:41
  • to any value i want, see my snippet? $rows[$k] ['running_days'] I am trying to change to "running_days" for the first first array key ["517f467ca2ec9"] Commented Apr 30, 2013 at 4:47

3 Answers 3

2

Please try this code it will help you

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);
Sign up to request clarification or add additional context in comments.

Comments

1

It seems you have multidimensional array. You can try this one...

// 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);

Comments

0
$rows[$k]['running_days'] = array_shift($rows[$k]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.