2014-10-10 2 views
0

나는 이런 식으로 뭔가를 보이는 배열을 가지고에있는 경우PHP는 - 그것은 특정 값을 포함하고 이러한 배열은 특정 순서

Array 
(
    [0] => Array 
     (
      [region_id] => 1 
      [region_content] => news2 
     ) 

    [1] => Array 
     (
      [region_id] => 2 
      [region_content] => something_else 
     ) 

    [2] => Array 
     (
      [region_id] => 3 
      [region_content] => news 
     ) 

) 

나는 그것으로 몇 가지를 할 필요가 ... 배열 순서를 변경 ..

배열에 newsnews2이 모두 포함되어 있는지 확인하고, 그렇다면 news2가 뉴스보다 먼저 표시되면 위치를 전환하십시오.

그래서 결과 배열은 다음과 같이 보일 것이다 :

Array 
(
    [0] => Array 
     (
      [region_id] => 1 
      [region_content] => news 
     ) 

    [1] => Array 
     (
      [region_id] => 2 
      [region_content] => something_else 
     ) 

    [2] => Array 
     (
      [region_id] => 3 
      [region_content] => news2 
     ) 

) 

그래서 내가 순서를 변경하는 방법을 다음 배열을 확인하는 방법에 약간의 도움이 필요합니다.

+0

아무 것도 시도해 보지 않으셨습니까? 예제 코드 –

+0

만약 내가 솔직하다면, 내 두뇌가 튀어 나와 어디서부터 시작해야할지 생각할 수 없다. – Tom

답변

0

그것은 또는 최선의 방법을 수행하는 효율적인 방법에서 멀리, 그러나 목적을 위해 설명의 :

<?php 
$collection = [ 
    [ 
     'region_id' => 1, 
     'region_content' => 'news2' 
    ], 
    [ 
     'region_id' => 2, 
     'region_content' => 'something else' 
    ], 
    [ 
     'region_id' => 3, 
     'region_content' => 'news' 
    ], 
]; 

$occurrences = 0; 
$final = ''; 
foreach ($collection as $sub) { 
    if (in_array($sub['region_content'], ['news', 'news2'])) { 
     $occurrences++; 
     $final = $sub['region_content']; 
    } 
} 

$toSwitch = ($occurrences == 2) && $final == 'news'; 

if ($toSwitch) { 
    foreach ($collection as &$sub) { 
     if ($sub['region_content'] == 'news2') $sub['region_content'] = 'news'; 
     elseif ($sub['region_content'] == 'news') $sub['region_content'] = 'news2'; 
    } 
} 

var_dump($collection); 

하면 region_content 중 하나 news 또는 news2 우리가 변수 발생을 증가하는 것입니다 에스. 우리가 정확히 두 사건을 기대하고 있으므로 - newsnews2 그리고 우리는 news2이 먼저 있는지 확인하고 있습니다. 따라서 변수에 news이 채워지면 news2이 (가)보다 이전임을 확신 할 수 있습니다.

발생 위치 == 2와 news2의 첫 번째 결과는 위치를 전환해야하는 경우 부울 표현입니다.

여기에서 위치를 전환하는 것은 값을 변경하는 것과 다를 바 없습니다. 문자열이기 때문에 우리는 단지 그것을 하드 코딩했습니다. 중첩 된 콜렉션 인 경우 첫 번째 반복에서 해당 값을 추출 할 수 있습니다.

The result of the dump is: 

array (size=3) 
    0 => 
    array (size=2) 
     'region_id' => int 1 
     'region_content' => string 'news' (length=4) 
    1 => 
    array (size=2) 
     'region_id' => int 2 
     'region_content' => string 'something else' (length=14) 
    2 => & 
    array (size=2) 
     'region_id' => int 3 
     'region_content' => string 'news2' (length=5) 
+0

저것은 저를 위해 작동한다! 감사!!! – Tom

0

이것은 당신이 요구하는지 어떻게해야 :

// Check if both news and news2 exist and make sure news come before news2 
function checkNewsAndSwap($array) 
{ 
    // Obtain the indexes 
    $indexes = []; 
    foreach($array as $i => $v) { 
     if($v['region_content'] == 'news') { 
      $indexes[1] = $i; 
     } 
     elseif($v['region_content'] == 'news2') { 
      $indexes[2] = $i; 
     } 
    } 

    // Both news and news2 exist 
    if(isset($indexes[1]) && isset($indexes[2])) { 
     if($indexes[2] < $indexes[1]) {// If news comes after news2 
      // Swap them! 
      $tmp = $array[$indexes[1]]['region_content']; 
      $array[$indexes[1]]['region_content'] = $array[$indexes[2]]['region_content']; 
      $array[$indexes[2]]['region_content'] = $tmp; 
     } 
    } 

    return $array; 
} 

테스트 코드와 결과 현재 위치 : http://pastie.org/9637389

+0

거의 전부지만 부분 배열 전체를 전환하고 싶지는 않지만 region_content 값만 변경하면됩니다. – Tom

+0

그럼 다음에 질문에 지정하십시오 ... – Qualcuno

+0

어쨌든, 저는 코드를 업데이트했습니다 (두 줄에 [region_content ']를 추가하는 문제였습니다). 내 솔루션은 아직 한 번 배열을 반복하므로 허용 된 답변보다 훨씬 효율적입니다. @ 토륨 – Qualcuno

관련 문제