简体   繁体   中英

Replace array keys and values

For example I have this array:

Array (
[0] => Array (
 [id] => 45 [name] => Name1 [message] => Ololo [date_create] => 21:03:56 )
[1] => Array (
 [id] => 46 [name] => visitor [message] => Hi! [date_create] => 21:06:28 )
)

I need converting to:

Array (
 [id] => Array (
  [0] => 45, [1] => 46
 )
 [name] => Array (
  [0] => Name1, [1] => visitor
 )
 [message] => Array (
  [0] => Ololo, [1] => Hi!
 ) 
 [date_create] => Array (
  [0] => 21:03:56, [1] => 21:06:28
 )
)

I like to know a function for converting this,

Try this block of code:

// Assuming the array you have is called $mainArray.
// The output will be $outputArray.
$outputArray = array();

foreach ($mainArray as $index => $array) { // Iterate through all the arrays inside the main array.
// foreach ($mainArray as $array) { // Use this if the numeric index order doesn't matter.
    foreach ($array as $key => $value) { // Iterate through each inner array.
        // Load the multidimensional array with the first key as one of (id, name, message, date_create) and second key as the numeric index (if you need it).
        $outputArray[$key][$index] = $value;
        // $outputArray[$key][] = $value; // Use this if the numeric index order doesn't matter.
    }
}

print_r($outputArray);

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