Here’s my solution.
I’m still learning PHP (normally I work in Ruby), so I would be really grateful for any constructive criticism / pointers the rest of you could give me.
<?php
function convertArray($start){
$end = array();
$unique_keys = array();
// Get a list of all possible keys
for ($row = 0; $row < count($start); $row++){
for ($col = 0; $col < count($start[$row]); $col++){
array_push($unique_keys, $start[$row][$col]);
}
}
$unique_keys = array_unique($unique_keys);
sort($unique_keys);
// Create new array using these keys
for ($row = 0; $row < count($start); $row++){
for ($col = 0; $col < count($start[$row]); $col++){
$temp_array = array();
foreach ($unique_keys as $key){
$temp_array[$key] = in_array($key, $start[$row])? '1' : '0';
}
}
array_push($end, $temp_array);
}
return($end);
}
$start = array(
array('a', 'b', 'c'),
array('b', 'c'),
array('a', 'c')
);
print_r(convertArray($start));
I have a feeling my version might be reducable, but meh…
(Note: I changed the input variable to $in)
$keys = array_unique(array_merge_recursive($in))[0]; //Find all keys
$values = array_combine($keys,array_pad(array(),count($keys),0)); //Fill with 0's. Creating a 'row' for the matrix.
$replace = array_map(function($item) { return array_combine($item,array_pad(array(),count($item),1)); }, $in); //All my 1's.
$out = array_pad(array(),count($in),$values); //Matrix of 0's.
$out = array_replace_recursive($out,$replace); //Put the 1's in the matrix.
PHP belches array-to-string issues at me on my Replace line, but i’m not… entirely sure where i’m converting a string in there… anyway, it works.
Nice one StarLion. That’s really neat!
I hadn’t heard of array_replace_recursive or array_merge_recursive, so I’ve just been reading the docs for those.
Now my head is ready to explode