개발 Q&A

제목 php array 문법 질문 있습니다.
카테고리 PHP
글쓴이 ci늦둥이 작성시각 2021/03/03 00:25:13
댓글 : 6 추천 : 0 스크랩 : 0 조회수 : 5975   RSS

안녕하세요. php 초급자 입니다.

php array 부분을 보다 궁금한점이 있어 질문 올립니다.

 

다음과 같은 $temp_array 가 있습니다.

$temp_array = array(
	'0' => array(
		'id' => 'test_1', 
		'type' => 'first'
	),
	'1' => array(
		'id' => 'test_2',
		'type' => 'second'
	),
	'2' => array(
		'id' => 'test_3',
		'type' => 'third'
	) 
);

 

여기에 '0' 에 자식 array 를 추가하고 싶습니다.

원하는 그림은 다음과 같습니다.


$temp_array = array(
	'0' => array(
		'id' => 'test_1', 
		'type' => 'first', 
		'child' => array(
			'0' => array(
				'id' => 'test_1_child_1',
				'type' => 'first_child'
			), 
			'1' => array(
				'id' => 'test_1_child_2',
				'type' => 'first_child'
			)		
		)
	),
	'1' => array(
		'id' => 'test_2',
		'type' => 'second'
	),
	'2' => array(
		'id' => 'test_3',
		'type' => 'third'
	) 
);

 

제가 했던 방법은

$temp_add_array = array(
	'0' => array(
		'id' => 'test_1_child_1',
		'type' => 'first_child'
	),
	'1' => array(
		'id' => 'test_1_child_2',
		'type' => 'first_child'
	)
);

$i = 0;
foreach($temp_array as $entry) {
	if($entry['type'] == 'first') {
		if(!isset($entry['child'])) {
			$entry['child'] = array();
		}
		array_push($entry['child'], $temp_add_array[$i]);
		$i++;
	}
}

 

이런식으로 작성하였습니다.

 

이부분은 함수로 만들었구요.

자식을 추가한 $temp_array 를 return 하였습니다.

받는쪽에서 var_dump 를 찍어보니 child 가 생기지 않네요.

 

짐작하셨겠지만

$temp_array 나 $temp_add_array 는

$this->db->query($sql)->result_array() 로 받은 항목들 입니다.

 

이렇게 result_array 로 받은 항목에는 추가가 안되는 것인지

아니면 array 안에 array 추가하는게 안되는지

그것도 아니면 제가 잘못 코딩한 것인지...

(제가 잘못한 것이라 생각하고 있습니다.)

 

제가 잘못한 부분이 무엇인지와 어떻게 해결해야되는지 알고싶습니다.

 

도움 부탁드립니다.

감사합니다.

 

 다음글 부트스트랩 및 제이쿼리 net::ERR_CERT_DAT... (4)
 이전글 컨트롤러에서 모델 로드에 대해 궁금한 점이 있습니다 (2)

댓글

PureAni / 2021/03/03 09:02:15 / 추천 0

생각을 조금만 해보면 답이 나오는 질문입니다.

row 에 작성하셔서 그렇습니다.

원본 array 에 추가하세요.

변종원(웅파) / 2021/03/03 09:03:40 / 추천 0

1. 둘다 db에서 쿼리 실행을 통해 가져오는데 왜 나눠서 가져올까요? 1차적 해결방법은 join 쿼리로 해결할 수 있어 보입니다.

2. foreach 에서 $temp_array 를 $entry에 할당해서 $entry 배열에 데이터를 넣었죠. 당연히 $temp_array 는 그대로 일테구요.

$entry를 출력해보세요.

ci늦둥이 / 2021/03/03 09:53:38 / 추천 0

답글 달아주셔서 감사합니다.

PureAni  님.

원본 array 라 하심은 $temp_array 인가요?

$temp_array 에 추가하면 

$temp_array = array(
    '0' => array(
        'id' => 'test_1',
        'type' => 'first',
        'child' => array(
            '0' => array(
                'id' => 'test_1_child_1',
                'type' => 'first_child'
            ),
            '1' => array(
                'id' => 'test_1_child_2',
                'type' => 'first_child'
            )      
        )
    ),
    '1' => array(
        'id' => 'test_2',
        'type' => 'second'
    ),
    '2' => array(
        'id' => 'test_3',
        'type' => 'third'
    )
);

이 모양이 아닌

$temp_array = array(
    '0' => array(
        'id' => 'test_1',
        'type' => 'first'
    ),
    '1' => array(
        'id' => 'test_2',
        'type' => 'second'
    ),
    '2' => array(
        'id' => 'test_3',
        'type' => 'third'
    ), 
    '3' => array(
        'id' => 'test_1_child_1',
        'type' => 'first_child'
    ),
    '4' => array(
        'id' => 'test_1_child_2',
        'type' => 'first_child'
    )
);

이 모양이 되는것일텐데.. 제가 잘못이해한 거겠죠? ㅠㅠ

ci늦둥이 / 2021/03/03 10:10:06 / 추천 0

변종원(웅파) 님.

1. 말씀처럼 join 으로도 해결 가능한 부분이긴 합니다. db 가 오라클 이면 connect by 를 사용해도 되는 구조이기도 하구요.

하다보니 php 문법을 익히고자 이렇게 해보고 싶어져서요.

2. 말씀처럼 $entry 를 찍어보니 loop 안에서는 'child' 가 찍히는데 loop 밖에서는 'child' 가 없어집니다.

'child' 가 생기긴 했지만 $temp_array 의 row 에 할당이 안되어 보이는데.. 제가 뭘 놓치고 있는지 감이 안잡히네요...

 

var_dump 를 찍은 소스와 결과 입니다.

- 소스

$temp_array = array(
    '0' => array('id' => 'test_1', 'type' => 'first'),
    '1' => array('id' => 'test_2', 'type' => 'second'),
    '2' => array('id' => 'test_3', 'type' => 'third')
);

$temp_add_array = array(
    '0' => array('id' => 'test_1_child_1', 'type' => 'first_child'),
    '1' => array('id' => 'test_1_child_2', 'type' => 'first_child')
);

$i = 0;
foreach ($temp_array as $entry) {
    if ($entry['type'] == 'first') {
        if (!isset($entry['child'])) {
            $entry['child'] = array();
        }
        array_push($entry['child'], $temp_add_array[$i]);
        $i++;
    }

    var_dump($entry);
}
echo '-------- result $temp_array';
var_dump($temp_array);

-- 결과 화면


array (size=3)
  'id' => string 'test_1' (length=6)
  'type' => string 'first' (length=5)
  'child' => 
    array (size=1)
      0 => 
        array (size=2)
          'id' => string 'test_1_child_1' (length=14)
          'type' => string 'first_child' (length=11)

array (size=2)
  'id' => string 'test_2' (length=6)
  'type' => string 'second' (length=6)

array (size=2)
  'id' => string 'test_3' (length=6)
  'type' => string 'third' (length=5)

-------- result $temp_array
array (size=3)
  0 => 
    array (size=2)
      'id' => string 'test_1' (length=6)
      'type' => string 'first' (length=5)
  1 => 
    array (size=2)
      'id' => string 'test_2' (length=6)
      'type' => string 'second' (length=6)
  2 => 
    array (size=2)
      'id' => string 'test_3' (length=6)
      'type' => string 'third' (length=5)

 

고은연 / 2021/03/03 11:41:25 / 추천 0

이렇게 해 보시겠어요?

<?php
$temp_array = array(
    '0' => array(
        'id' => 'test_1',
        'type' => 'first'
    ),
    '1' => array(
        'id' => 'test_2',
        'type' => 'second'
    ),
    '2' => array(
        'id' => 'test_3',
        'type' => 'third'
    )
);

$child = array(
    '0' => array(
        'id' => 'test_1_child_1',
        'type' => 'first_child'
    ),
    '1' => array(
        'id' => 'test_1_child_2',
        'type' => 'first_child'
    )
);


$first_element = $temp_array[0];
$first_element['child'] = $child;
$temp_array[0] = $first_element;

echo '<pre>';
var_dump($temp_array);
echo '</pre>';

---

결과는 아래와 같아요.

array(3) {
  [0]=>
  array(3) {
    ["id"]=>
    string(6) "test_1"
    ["type"]=>
    string(5) "first"
    ["child"]=>
    array(2) {
      [0]=>
      array(2) {
        ["id"]=>
        string(14) "test_1_child_1"
        ["type"]=>
        string(11) "first_child"
      }
      [1]=>
      array(2) {
        ["id"]=>
        string(14) "test_1_child_2"
        ["type"]=>
        string(11) "first_child"
      }
    }
  }
  [1]=>
  array(2) {
    ["id"]=>
    string(6) "test_2"
    ["type"]=>
    string(6) "second"
  }
  [2]=>
  array(2) {
    ["id"]=>
    string(6) "test_3"
    ["type"]=>
    string(5) "third"
  }
}

 

ci늦둥이 / 2021/03/03 13:50:19 / 추천 0

고은연 님. 감사합니다!

알려주신 방법으로 해결하였습니다.

왜 그런지 이해는 좀 안되긴 하지만... 되니 일단은 다행입니다.

정말 감사합니다!!!

 

왜 그런지 찬찬히 살펴봐야겠네요.

감사합니다!