开发者

Patterns for building multidimensional array with unique key

Problem: Extract data from an object/array and represent this data using a multidimensional array with a unique key generated from the inner loop.

I always find myself building multidimensional arrays like this:

$final_array = array();
foreach ($table as $row) {
    $key = null;
    $data = array();
    foreach ($row as $col => $val) {
        /* Usually some logic goes here that does 
           some data transformation / concatenation stuff */
        if ($col=='my_unique_key_name') {
            $key = $val;
        }
        $data[$col] = $val;
    }
    if (!is_null($key) {
        if (!isset($final_array[$key]) {
            $final_array[$key] = array();
        }
        $final_array[$key][] = $data;
    }
}

I can't help but wonder if I'm constantly doing this out of habit, but it feels kind of verbose with all the key-checking and whatno开发者_如何学JAVAt. Is there a native function I am not utilizing? Can this be refactored into something more simple or am I overthinking this?


Why are you always doing that? Doesn't seem the common kind of stuff one works with on a day to day basis... Anyway, that's kinda cryptic (an example would be nice) but have you though of using an MD5 hash of the serialized dump of the array to uniquely define a key?

$key = md5(serialize($value));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜