开发者

Extract data from nested arrays

I have the following array (via var_dump) $results:

array(4) { 
    [0]=> array(5) { 
        [0]=> array(1) { ["evtId"]=> string(1) "2" } 
        [1]=> array(1) { ["evtId"]=> string(1) "3" } 
        [2]=> array(1) { ["evtId"]=> string(1) "4" } 
        [3]=> array(1) { ["evtId"]=> string(1) "5" } 
        [4]=> array(1) { ["evtId"]=> string(1) "6" } 
    [1]=> array(5) { 
        [0]=> array(1) { ["evtLocation"]=>开发者_开发知识库; string(2) "11 St Paul" } 
        [1]=> array(1) { ["evtLocation"]=> string(5) "12412 Horace St" } 
        [2]=> array(1) { ["evtLocation"]=> string(14) "Friends Center" } 
        [3]=> array(1) { ["evtLocation"]=> string(14) "Friends Center" } 
        [4]=> array(1) { ["evtLocation"]=> string(14) "Friends Center" } 
    [2]=> array(5) { 
        [0]=> array(1) { ["evtDate"]=> string(1) "11/12/2011" } 
        [1]=> array(1) { ["evtDate"]=> string(1) "06/05/2012" } 
        [2]=> array(1) { ["evtDate"]=> string(1) "10/10/2010" } 
        [3]=> array(1) { ["evtDate"]=> string(1) "06/06/2012" } 
        [4]=> array(1) { ["evtDate"]=> string(1) "10/12/2012" } 
    [3]=> array(5) { 
        [0]=> array(1) { ["evtType"]=> string(4) "Fun" } 
        [1]=> array(1) { ["evtType"]=> string(6) "Random" } 
        [2]=> array(1) { ["evtType"]=> string(9) "Childcare" } 
        [3]=> array(1) { ["evtType"]=> string(9) "Childcare" } 
        [4]=> array(1) { ["evtType"]=> string(9) "Childcare" } 

I'm using this array to pull database information into a function that builds a table. However, I need this to end up in the following format:

$rows[] = array('2', '11 St Paul', '11/12/2011', 'Fun'); 

I've really only been able to get this far:

foreach ($events as $field_arr) {
  //this gives me 4 arrays, each array containing all of the records for one field type.
}

Now I need to loop through each of the four arrays, take one value from the same index and add it to the $rows[] array, which I can pass to the table building function. I've tried variations of the following (inside the initial foreach loop)

 $x = count($result[0]); //this gives the number of fields
 for ($i = 0; $i < $x; $i++) {
    rows[$i] = $field_array[$i];
 }

I've been trying variations for half the day, with little luck (I'm ending up with arrays containing 4 times as many elements as I need, and having a hard time getting rid of the final array keys (['evtType'] etc). If anyone can help point me in the right direction I'd greatly appreciate it.


Most code posted here seems quite verbose, so here's a short version:

$rows = array();
foreach ($results as $pairs)
{
    foreach ($pairs as $rowNumber => $pair)
    {
        // current($pair) will give you the value
        // you could use key($pair) to get the key too
        $rows[$rowNumber][] = current($pair);
    }
}

That's pretty much it. Each element of $results holds a list of key=>value pairs and we're only interested in the value of each pair. The index of the pair is the index of the row, which we store in $rowNumber. I've run it and it seems to produce the expected results.


Probably the shortest way:

$combined = array_map(function ($a, $b, $c, $d) { return $a + $b + $c + $d; }, $results[0], $results[1], $results[2], $results[3]);

Or, automatically scalable to accommodate any number of result elements:

$combined = call_user_func_array('array_map', array_merge(array(function () {
                $args = func_get_args();
                return call_user_func_array('array_merge', $args);
            }), $results));

Both merge every nth element of each array node into a new array.


Assuming the array is always the right sizes (and not "jagged")

$field_count = count($original);
$item_count = count($original[0]);

$items = array_fill(0,$item_count,array());

for($i = 0; $i < $item_count; $i++){
    for($j = 0; $j < $field_count; $j++){
        $inner = $original[$j][$i][0]; // Grab the innermost array
        $temp = array_values($inner); // Only take the values, discard "evtId" etc.
        // (PHP doesn't support array indices right after function call)
        $items[$i][] = $temp[0]; // Append value to item
    }
}

BTW, you can often use var_export(x,true) instead of var_dump(x) to get re-pasteable PHP.


Assuming your original array is assigned to a variable named $data:

$data = array(...);

$colCount = count($data);
$rowCount = $colCount > 0 ? count($data[0]) : 0;

$rows = array();
for ($r = 0; $r < $rowCount; $r++) {
    $record = array();
    for ($c = 0; $c < $colCount; $c++) {
        $key = key($data[$c][$r]);
        $value = $data[$c][$r][$key];
        $record[$key] = $value;
    }
    $rows[] = $record;
}


As much as the data is stacked into each other, you need to fetch from it. Just not only create one iteration but four, as your data structure has four levels as well:

foreach($original as $fieldIndex => $fields) { 
    foreach($fields as $valueIndex => $envelope) {
        foreach($envelope as $valueEntry) {
            foreach($valueEntry as $key => $value) {
                printf("%d - %d - %s: '%s'\n", $fieldIndex, $valueIndex, $key, $value);
                $build[$valueIndex][$key]=$value;
            }
        }
    }
}

var_dump($build);

I've put some output inside there so you can see what has been collected in the innermost part. That's the place where all data is collected and you can re-order it according to your needs.

This only works if you have always the same number of elements on each corresponding level to get a result that's well formed. However, the code-example already works when there are always the same level nesting, so not every item needs to have all keys.

Edit: corrected from three to four levels.


This is not intended toward the poster, but to those who criticize me for saying I did not test my code. DISCLAIMER: I am not here to write your application for you. I will attempt to provide you with usable code, but I in no way guarantee that this is drag and droppable, plug and play, or anything else. If you want that type of service, then please hire myself or one of the many other competent professional developers you find on this site.

That being said... this code should get you going in the direction you need to go, I have tested it, but do not guarantee it will work with your particular array structure, but should be enough to give you an idea of what you need to do.

Hope this helps!

foreach($events as $value1) {

 foreach($value1 as $value2) {

   $new_arr[] = array(
    'evtId' => $value2['evtId'],
    'evtLocation' =>$value2['evtLocation'],
    'evtDate' => $value2['evtDate'],
    'evtType' =>$value2['evtType']) ;
   }

}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜