2016-04-24 179 views
1

我有一個陣列(從MySQL)拆分多維陣列​​分成單個陣列:PHP

Array ( 
    [0] => Array ( 
     [heading] => Page Name change 
     [name] => Page_Name_change 
     [menu] => online 
    ) 
    [1] => Array ( 
     [heading] => Lorem ipsum dolor 
     [name] => Lorem_ipsum_dolor_ 
     [menu] => akshaya 
    ) 
    [2] => Array ( 
     [heading] => fgdfgfdgdfgdf 
     [name] => fgdfgfdgdfgdf 
     [menu] => akshaya 
    ) 
) 

我需要將它分成單獨的陣列中,基礎上[menu],檢查這個PHP

function getpage() { 
    $query = "SELECT heading,name,menu FROM pages"; 
    $res = $this->_conn->query($query); 
    while ($row = mysqli_fetch_assoc($res)) { 
     $result[] = $row; 
    } 
    for ($i=0; $i < count($result); $i++) { 
     if (strcmp($result[$i]['menu'],'akshaya') == 0) { 
      for ($j=0; $j < count($result[$i]) ; $j++) 
       $menu = $result[$i][$j]; 
     } 
    } 
    //if(strcmp($row['menu'],'akshaya')==0) { } 
    return $menu; 
} 

預期的結果是每個菜單段具有來自初始陣列的元素列表的陣列,如下所示:

[ 
    'online' => [ 
     [ 
      'heading' => '...', 
      'name' => '...', 
     ], 
    ], 
    'akshaya' => [ 
     [...], 
     [...], 
    ], 
] 

MySql Data base

其用於顯示的導航菜單&子菜單,

enter image description here

回答

1
function getpage() { 
    $query = "SELECT heading,name,menu FROM pages"; 
    $res = $this->_conn->query($query); 
    while ($row = mysqli_fetch_assoc($res)) { 
     $result[] = $row; 
    } 

    $menu = []; 
    foreach ($result as $menuItem) { 
     $menu[$menuItem['menu']][] = $menuItem; 
    } 

    return $menu; 
} 
+0

解決了......你的答案工作.. –

+0

你能否請標記正確答案? –

0
function getpage() { 
    $query = "SELECT heading,name,menu FROM pages"; 
    $res = $this->_conn->query($query); 
    while ($row = mysqli_fetch_assoc($res)) { 
     $result[] = $row; 
    } 

    $menu = []; 
    foreach ($result as $menuItem) { 
     $menu[$menuItem['menu']][] = $menuItem; 
    } 

    return $menu; 
} 



<?php 
$nav=new Pages(); 
$res=$nav->getpage(); 
//print_r($res); 
echo "<br>"; 
foreach ($res as $r){ 
    // print_r($r); 
    echo "<br>"; 
    foreach($r as $rc){ 

     if (strcmp($rc['menu'],'akshaya') == 0) { 
      $akshaya[]=$rc; 
    } 
    echo "<br>"; 
} 
} 
    print_r($akshaya); 
echo count($res); 

?> 

輸出:

Array ([0] => Array ([heading] => Lorem ipsum dolor [name] => Lorem_ipsum_dolor_ [menu] => akshaya) [1] => Array ([heading] => fgdfgfdgdfgdf [name] => fgdfgfdgdfgdf [menu] => akshaya))