2013-07-28 5 views
-3
$test = array (
    "test1" => array("a" => "1", "b" => "2", "c" => "3") 
); 

나는 위와 같은 배열을 가지고 있습니다. ı 루프에서 값을 밀어 넣으려고합니다. 어떻게 가능할까요? 말해 주시겠습니까?PHP 키 - 값 배열 푸시

+1

? 최종 결과로 원하는 것은 무엇입니까? –

+1

'$ test [ 'test1'] [$ newKey] = $ newValue;와 유사합니까? –

답변

-1

방금 ​​같이 할 수있는 새로운 가치 밀어해야하는 경우 :

$test['test1']['newkey1'] = 'newvalue1'; 
$test['test1']['newkey2'] = 'newvalue2'; 
$test['test1']['d'] = '4'; 

또는

$test['test2'] = array(...); 
+1

왜 이전 답변을 수정하지 않으셨습니까? –

+0

친구 감사합니다! –

-1

그냥 foreach를 사용하십시오!

foreach($test['test1'] as $key => $value){ 
    echo "$key = $value"; 
} 
+1

나는 읽고 싶어하지 않는다. 나는 새로운 것을 추진하고 싶다. –

+0

2 차원 배열이기 때문에 2x foreach 루프를 사용해야합니다. 처음 실행하면 $ value 필드에 배열이 포함됩니다. – KarelG

-1

당신은 foreach 문을 사용할 수 있습니다.

foreach ($test as $key => $value) // Loop 1 times 
{ 
    // $key equals to "test1" 
    // $value equals to the corespondig inner array 

    foreach ($value as $subkey => $subvalue) // Loop 3 times 
    { 
     // first time $subkey equals to "a" 
     // first time $subvalue equals to "1" 
     // .. and so on 
    } 
} 

하나만 귀하의 예를 들어 첫 번째 루프를 건너 뛸 수 있습니다로 첫 번째 부분 배열을 기대하는 경우 :

foreach ($test["test1"] as $subkey => $subvalue) // Loop 3 times 
{ 
    // first time $subkey equals to "a" 
    // first time $subvalue equals to "1" 
    // .. and so on 
} 

편집 : 당신은 당신이 사용할 수없는 내부 데이터를 푸시하려면 $ key와 $ value와 같은 지역 변수. 원래의 배열 변수를 나타 내기 위해 $ key를 사용할 수 있습니다. 예를 들면 다음과 같습니다.

foreach ($test["test1"] as $subkey => $subvalue) // Loop 3 times 
{ 
    // changing current value 
    $test["test1"][$subkey] = "new value"; 

    // pushing new member 
    $test["test1"][] = "some value" 
} 
+0

이렇게하면 값을 반복하는 데 도움이되지만 배열에 새 값을 적용하려고합니다. –

+0

답변을 수정했습니다. –

0

값을 푸시 할 대상을 지정하지 않았습니다.

// array to push content 
$newArray = array(); 

// loop through first dimensional of your array 
foreach ($test as $key => $hash) { 
    // your hash is also an array, so again a loop through it 
    foreach ($hash as $innerkey => $innerhash) { 
     array_push($newArray, $innerhash); 
    } 
} 

배열에는 "1", "2", "3"만 포함됩니다. 다른 출력물을 원하면 원하는 출력물을 답장하십시오.

0

array_push() 기능을 사용하여 배열의 요소를 푸시 할 수 있습니다. array_push()은 배열을 스택으로 처리하고 전달 된 변수를 배열의 끝으로 푸시합니다. 배열의 길이는 푸시 된 변수의 수만큼 증가합니다.

$test = array (
    "test1" => array("a" => "1", "b" => "2", "c" => "3") 
); 

$test[] = "YOUR ELEMENT"; 

or 

array_push($test, 'YOUR DATA', 'ANOTHER DATA'); 


/* If you use array_push() to add one element to the array it's better to use 
$array[] = because in that way there is no overhead of calling a function. 

array_push() will raise a warning if the first argument is not an array. 
This differs from the $var[] behaviour where a new array is created. */ 

함수 참조 : http://php.net/manual/en/function.array-push.php

을 밀어