2012-05-17 2 views
2

내 응용 프로그램에 알파벳 순서로 항목 목록을 표시하고 각 섹션 블록의 첫 번째 태그 이름으로 나누는 다음 코드가 있습니다.PHP : 알파벳 순서로 데이터 배열을 분할

예 : 나는 어려운 배열 등에게의 다른 데이터에 액세스 할 찾는거야, 지금 배열을 분할 한 그러나

<?php 

    foreach($topics as $currentTopic): 
     $thisLetter = strtoupper($currentTopic['Topic']['title'][0]); 
     $sorted[$thisLetter][] = $currentTopic['Topic']['title']; 
     unset($thisLetter); 
    endforeach; 

    foreach($sorted as $key=>$value): 

     echo '<h3 class="alpha"><span>'.$key.'</span></h3>'; 
     echo '<ol class="tags main">'; 

     foreach($value as $thisTopic): 

      echo '<li class="tag"><em>0</em>'; 
      echo $this->Html->link('<strong>'.$thisTopic['Topic']['title'].'</strong>', 
         array('controller'=>'topics','action'=>'view','slug'=>$thisTopic['Topic']['slug']), 
         array('escape'=>false,'rel'=>'tag')); 
      echo '</li>'; 
     endforeach; 

     echo '</ol>'; 

    endforeach; 

    ?> 

:

A 
animal 
amazing 

B 
bat 
baseball 

코드는 다음과 같다 $ thisTopic 변수가 제목과 다른 필수 데이터를 저장하기 때문에 링크에 사용되는 주제 슬러그로 사용됩니다. 토픽 4 관련 게시물

<em>4</em>은 현재 내가 뭘 일을 보여줄 경우 오류를 준다 그래서 나는 또한 TopicPost뿐만 아니라 <em>에서 계산 보여주고 싶은 : 나는 배열을 분할 한 Fatal error: Cannot use string offset as an array 때문에 ...

아무도 도와 줄 수 있습니까? 나는 $ 주제의 배열을 디버깅 할 경우

나는 다음과 같은 얻을 : 당신은 단지 항목의 제목을 저장하기 때문에

array(
    (int) 0 => array(
     'Topic' => array(
      'id' => '5', 
      'title' => 'amazing', 
      'slug' => 'amazing' 
     ), 
     'TopicPost' => array(
      (int) 0 => array(
       'id' => '9', 
       'topic_id' => '5', 
       'post_id' => '101' 
      ) 
     ) 
    ), 
    (int) 1 => array(
     'Topic' => array(
      'id' => '4', 
      'title' => 'amazingness', 
      'slug' => 'amazingness' 
     ), 
     'TopicPost' => array(
      (int) 0 => array(
       'id' => '8', 
       'topic_id' => '4', 
       'post_id' => '100' 
      ), 
      (int) 1 => array(
       'id' => '12', 
       'topic_id' => '4', 
       'post_id' => '101' 
      ), 
      (int) 2 => array(
       'id' => '4', 
       'topic_id' => '4', 
       'post_id' => '119' 
      ) 
     ) 
    ),... 
+0

업데이트를이로하십시오? – Cameron

답변

4

당신은 오류가 발생합니다.

내가 대신 제목 만의 전체 주제의 정보를 저장하는 것이 좋습니다 : 다음

$orderedTopics= array(); 
foreach ($topics as $topic) { 
    $orderedTopics[strtoupper($topic['Topic']['title'][0])][] = $topic; 
} 

과, 그것을 표시 :

foreach ($orderedTopics as $section=>$topics) { 
    echo $section; 
    foreach ($topics as $topic) { 
    echo 'Title: ' . $topic['Topic']['title']; 
    echo 'Body: ' . $topic['Topic']['body']; 
    //etc... 
    } 
} 
+0

굉장히 가벼운 코드;) 고마워. – Cameron

관련 문제