In my data mining project, I'm given a complicated, huge multidemensional array of arrays that contains all the info I require, except that I have to perform a "fix" on it before I can process it. I've written some code that takes care of the issue, but it's taking way too long for the huge amount of data I have to "fix," and I'm hoping someone can help me find a more efficient solution.
Essentially, the type of array I'm working with is first indexed by an integer, as any run-of-the-mill array would, i.e. $x[0], $x[1], $x[2]
, except that each element is an associative array that contains key-pair values that I need (such as $x[0]['item'], $x[0]['price']
), however one key is stored a bit deeper, the ID.
An ID number exists in the array as $x[0]['@attributes']['id']
, and I would like to simplify the structure by duplicating this info along with the other key pairs, like $x[0]['id']
.
The data set I'm working with is large, but here is a simplified example of my situation:
$attrib1 = array('id'=>'101');
$item1 = array('@attributes'=>$attrib1, 'item'=>'milk', 'price'=>'3.50');
$attrib2 = array('id'=>'102');
$item2 = array('@attributes'=>$attrib2, 'item'=>'butter', 'price'=>'2.45');
$attrib3 = array('id'=>'103');
$item3 = array('@attributes'=>$attrib3, 'item'=>'bread', 'price'=>'1.19');
$items = array($item1, $item2, $item3);
echo "Starting data - items using itemid as attribute:\n";
print_r($items);
# set item numbers by key instead of attribute
$i=0;
while(isset($items[$i]['@attributes']['id'])) {
$items[$i]['itemid'] = $items[$i]['@attributes']['id'];
#unset($items[$i]['@attributes']);
$i++;
} # while
echo "\nDesired result - items using itemid as key:\n";
print_r($items);
Here is the output from that above example:
Starting data - items using itemid as attribute:
Array
(
[0] => Array
(
[@attributes] => Array
(
[id] => 101
)
[item] => milk
[price] => 3.50
)
[1] => Array
(
[@attributes] => Array
(
[id] => 102
)
[item] => butter
[price] => 2.45
)
[2] => Array
(
[@attributes] => Array
(
[id] => 103
)
[item] => bread
[price] => 1.19
)
)
Desired result - items using itemid as key:
Array
(
[0] => Array
(
[@attributes] => Array
(
[id] => 101
)
[item] => milk
[price] => 3.50
[itemid] => 101
)
[1] => Array
(
[@attributes] => Array
(
[id] => 102
)
[item] => butter
[price] => 2.45
[itemid] => 102
)
[2] => Array
(
[@attributes] => Array
(
[id] => 103
)
[item] => bread
[price] => 1.19
[itemid] => 103
)
)
Note the added [itemid] key-value pair in the desired result. Is there a faster / more elegant way of accomplishing this? I've looked at some of PHP's fancy array functions, but I can't wrap my head around this more complicated situation to make use of them. Any ideas?