简体   繁体   中英

create a workable array from existing array in php

I have trouble understanding arrays and I was wondering if someone could help me reformat an existing array in php.

This is the existing array:

Array
(
[item] => Array
(
    [0] => item listing 1
    [1] => item listing 2
)

[description] => Array
(
    [0] => item testing description
    [1] => item testing description
)

[rate] => Array
(
    [0] => 1.00
    [1] => 2.00
)

[itemid] => Array
(
    [0] => 1
    [1] => 2
)
)

I want it to look like this:

Array
(
[0] => Array
(
    [item] => item listing 1
    [description] => item testing description
    [rate] => 1.00
    [itemid] => 1
)
[1] => Array
(
    [item] => item listing 2
    [description] => item testing description
    [rate] => 2.00
    [itemid] => 2
)

If the length of all the sub-arrays in the first one are the same this should work.

Assume the first array above is in a variable $inArray ; the new array is $outArray .

$outArray = array();
$iLength  = count($inArray['item']);
for($i=0; $i<$iLength; $i++) {
    $outArray[] = array(
        'item'        => $inArray['item'][$i],
        'description' => $inArray['description'][$i],
        'rate'        => $inArray['rate'][$i],
        'itemid'      => $inArray['itemid'][$i]);
}

Ok so if your master array is called $master. Then you'd do something like this:

$newArr = array();
foreach ($master as $key => $subArray) {
    foreach ($subArray as $k2 => $value) {
        $newArr[$k2][$key] = $value;
    }
}

Working for your specific use case(copy/paste on a blank php):

$master = array( 
  'itemid' => array(1, 2),
  'items' => array('item listing 1', 'item listing 2'),
  'description' => array('item testing description', 'item testing description'),
  'rate' => array(1.10, 2.10)
);

$newItems = array();
foreach($master['itemid'] as $index => $id) {
  $newItem = array(
    'itemid' => $id,
    'item' => $master['items'][$index],
    'description' => $master['description'][$index],
    'rate' => $master['rate'][$index],
  );
  $newItems[] = $newItem;
}

echo '<pre>';
print_r($newItems);
echo '</pre>';

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