다음 출력을 아래에서 얻고 싶습니다. 나는 foreach를 사용하여 다음을 수행하지만 번호를 인쇄하지는 않습니다. '0', '1'또는 '2'를 얻는 대신 빈칸을 얻습니다.foreach를 사용하여 숫자를 배열의 키 값으로 설정하는 방법은 무엇입니까?
예상대로 배열을 인쇄 할 수 있습니까?
$results = array (
array(
'body' => 'somevalue1',
'title' => 'somevalue1',
'type' => 'foo'
),
array(
'body' => 'somevalue2',
'title' => 'somevalue2',
'type' => 'foo'
),
array(
'body' => 'somevalue3',
'title' => 'somevalue3',
'type' => 'bar'
),
array(
'body' => 'somevalue4',
'title' => 'somevalue4',
'type' => 'foobar'
),
array(
'body' => 'somevalue5',
'title' => 'somevalue5',
'type' => 'foobar'
),
array(
'body' => 'somevalue6',
'title' => 'somevalue6',
'type' => 'foobar'
),
);
원하는 출력 :
$values = array(
'foo' => array(
[0] => array(
'body' => 'some value',
'title' => 'some value'
),
[1] => array(
'body' => 'other value',
'title' => 'other value'
)
),
'bar' => array(
[0] => array(
'body' => 'some value',
'title' => 'some value'
)
),
'foobar' => array(
[0] => array(
'body' => 'some value',
'title' => 'some value'
),
[1] => array(
'body' => 'other value',
'title' => 'other value'
),
[2] => array(
'body' => 'other value',
'title' => 'other value'
)
),
);
번호 :
$value_index = array(); //used to keep track of number of values under field1
foreach($results as $row) {
//get number of field1's. if none, then set to 0
$num = isset($value_index[$row.type]) ? $value_index[$row.type] : 0;
/* performs some logic here */
//store values in temp array
$temp['body'] = $row.body;
$temp['title'] = $row.title;
$values[$row.type][$num] = $temp;
$value_index[$row.type] = $num + 1;
}//end foreach
현재 문제점 :
- $ 값의 [$ row.type [$ NUM = $ 임시 ;
- 는 $ NUM 절약 등, '1'을 '0'으로되지는
목표 '로 저장된다
- 그룹의 모든 유형을 함께. 예를 들어, type = foo 인 경우 나중에 유형별로 인쇄 할 수 있도록 그룹화하려고합니다. 그래서 모든 요소를 인쇄 할 경우 형식 = foo 및 그룹화 된 배열에 많은 요소가 있으면 '0', '1', '2'등을 통해 액세스 할 수 싶습니다.
원하는 출력 시켰지? 코드에서 – nogad
이 명확하지 않은 이유는 'foo'= = 대신 – Bluetree
@user2951257입니다. '$ 결과'는 어디에서 왔습니까? 게시 해주세요 – Bluetree