2014-12-04 5 views
-2

저는 PHP를 사용하는 초보자이며 연관 배열을 사용하여 concantenate 할 문자열을 가지고 있습니다.하지만 아이디어가 있지만 배열 내의 배열을 사용합니다.PHP에서 연관 배열을 만드는 방법

$GLOBALS['batman'] = /*** Find the appropriate associative array. ***/; 

function robin() 
{ 

    $z = 'flash'; 
    return $z; 
} 

function ironman() 
{ 
    $answer = $GLOBALS['batman']['superman']['spiderman'][robin()][0]; // "The sum is " - this is a string 
    $answer .= $GLOBALS['batman']['superman']['spiderman'][robin()][1] // 14 - this is an integer 
     + $GLOBALS['batman']['superman']['spiderman'][robin()]['hulk'][2]; // 11 - this is an  integer 
    return $answer; 
} 

echo ironman(); // this should print out "The sum is 25" 
+3

초보자는 '$ GLOBALS'을 전혀 사용하지 않아야합니다. 그것에 대해 더 많이 배우는 동안, 당신은 당신도 그것을 필요로하지 않는다는 것을 깨닫게 될 것입니다. –

+0

실제로 이것은 나의 서브에 대한 나의 좌석입니다. 그리고 이것은 PHP를 배울 수있는 첫 번째 시간이며, 제 교수는이 운동을 제공하고이 글로벌에 대해 혼란 스럽습니다. – user14

답변

3

아래는 학생에게 전달할 수있는 종류의 코드의 예로서 "교수"에게 보내는 것입니다. $GLOBALS과 같은 것을 언급하는 것은 모든 교과서에서 근절되어야합니다. 변수를 함수에 전달하는 법을 배우는 것이 훨씬 더 유용합니다. 이 코드를 실행하면 실종 무엇으로

<?php 

error_reporting(~0); 

function robin() 
{ 
    $z = 'flash'; 
    return $z; 
} 

function ironman(array $data) 
{ 
    return sprintf('%s%d', 
    $data['batman']['superman'][robin()][0], 
    $data['batman']['superman'][robin()][1] + $data['batman']['superman'][robin()]['hulk'][2] 
); 
} 

$data = array(); // fill in appropriate data structure here 
echo ironman($data); // this should print out "The sum is 25" 

이제, 당신은 인터프리터에서 힌트를 얻을 것이다 :

PHP Notice: Undefined index: batman in assoc.php on line 15 

그것은 $data 배열이 'batman' 인덱스가 없음을 의미한다 다시 실행

$data = array(
    'batman' => array(), 
); 

는 다음과 같은 표시됩니다 : 이것은 당신이 추가하는 방법입니다

당신의 $data['batman'] 배열이 'superman' 인덱스가 누락 의미
PHP Notice: Undefined index: superman in assoc.php on line 15 

; 그래서 당신은뿐만 아니라 누락 된 인덱스를 추가 : 인터프리터가 불평을 중지하고도 올바른 대답을해야 될 때까지

$data = array(
    'batman' => array(
    'superman' => array(), 
), 
); 

은 기본적으로 당신이 구조를 변경 유지.

관련 문제