1

aside from doing the actual work of iterating through an associative array, pushing a value into a new array and setting that equal the array of remaining fields, is there an array function built into PHP that would do something like this?

if so, what is it?

i would be changing the following:

array(
    [0] => array(
        [created] => 12512512,
        [name] => something
    )
)

into something like this:

array(
    [12512512] => array(
        [created] => 12512512,
        [name] => something
    )
)
4
  • Can you please paste your code here so I can help you? Commented Aug 9, 2012 at 7:32
  • Not that I know of, no, but if your array elements are of the same consistent structure (ie an array having a key of created), then it's easy enough to write a simple function to do that. Commented Aug 9, 2012 at 7:33
  • @JackManey ah, thats what i suspected.. and it makes me kind of sad :) Commented Aug 9, 2012 at 7:35
  • This is similar to array_flip... but not quite, you will need to write a custom function to perform this. Commented Aug 9, 2012 at 7:35

4 Answers 4

1

Flip the value and remove the old one in the same array... this should be fine provided the created value doesn't overwrite one of the existing entries, which I highly doubt since created seems to be a timestamp.

foreach($myArray as $index => $entry) {
    $myArray[$entry['created']] = $entry;
    unset($myArray[$index]);
}

Or you could keep both copies and use references to save on ram.

foreach($myArray as &$entry)
    $myArray[$entry['created']] =& $entry;
Sign up to request clarification or add additional context in comments.

Comments

1

i don't know what you realy want to do .... maybe this could you help

<?php
   $new = array();
   foreach($oldArr as $arr) {
        $new[$arr['created']] = $arr;

   }
   print_r($new);
?>

1 Comment

You could save some RAM by doing it all in the same array, and un-setting the old value, or if you need to keep both, set the value by reference =&
1

if first array is $a

foreach ($a as $v){
    $newarray[$v['created']] = $v;
}

Comments

-1

please try code given below

$arrs = array();
$arrs[0]['created'] = 1252;
$arrs[0]['name'] = 'A';

$narrs = array();
foreach($arrs AS $arr){
 $narrs[$arr['created']]['created'] = $arr['created'];
 $narrs[$arr['created']]['name'] = $arr['name'];
}

echo "<pre>";
print_r($narrs); echo "</pre>";

thanks

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.