source

PHP는 array_push를 사용하여 요소를 다차원 배열에 추가합니다.

factcode 2022. 9. 8. 21:49
반응형

PHP는 array_push를 사용하여 요소를 다차원 배열에 추가합니다.

저는 다차원 배열 $md_array를 가지고 있는데, 서브어레이 레시피_type과 테이블에서 데이터를 읽는 루프에서 나오는 요리에 더 많은 요소를 추가하고 싶습니다.

루프에서 각 행에 대해 새 테이블 $newdata를 만듭니다.

$newdata =  array (
          'wpseo_title' => 'test',
          'wpseo_desc' => 'test',
          'wpseo_metakey' => 'test'
        );

그리고 나서,array_push()$newdata 어레이를 다음 다차원 어레이에 추가해야 합니다.

$md_array= array (
     'recipe_type' => 
      array (
        18 => 
        array (
          'wpseo_title' => 'Salads',
          'wpseo_desc' => 'Hundreads of recipes for Salads',
          'wpseo_metakey' => ''
        ),
        19 => 
        array (
          'wpseo_title' => 'Main dishes',
          'wpseo_desc' => 'Hundreads of recipes for Main dishes',
          'wpseo_metakey' => ''
        )
      ),
     'cuisine' => 
      array (
        22 => 
        array (
          'wpseo_title' => 'Italian',
          'wpseo_desc' => 'Secrets from Sicily in a click',
          'wpseo_metakey' => ''
        ),
        23 => 
        array (
          'wpseo_title' => 'Chinese',
          'wpseo_desc' => 'Oriental dishes were never this easy to make',
          'wpseo_metakey' => ''
        ),
        24 => 
        array (
          'wpseo_title' => 'Greek',
          'wpseo_desc' => 'Traditional Greek flavors in easy to make recipies',
          'wpseo_metakey' => ''
        )
      ) 
    );

array_push를 사용하여 recipe_type 배열에 새 요소(배열)를 추가하기 위한 구문은 무엇입니까?다차원 어레이를 이해할 수 없어서 조금 혼란스러워요.

연관 배열 내에서 증분 순서로 데이터를 추가하려면 다음과 같이 하십시오.

$newdata =  array (
      'wpseo_title' => 'test',
      'wpseo_desc' => 'test',
      'wpseo_metakey' => 'test'
    );

// for recipe

$md_array["recipe_type"][] = $newdata;

//for cuisine

 $md_array["cuisine"][] = $newdata;

마지막 인덱스가 무엇이냐에 따라 레시피나 요리에 추가됩니다.

배열 푸시는 보통 순차 인덱스가 $arr[0], $ar[1]일 때 배열에서 사용됩니다.연관 배열에서 직접 사용할 수 없습니다.그러나 서브 어레이에는 이런 종류의 인덱스가 있기 때문에 계속 이렇게 사용할 수 있습니다.

array_push($md_array["cuisine"],$newdata);

다차원 배열에서 엔트리가 다른 배열인 것처럼 array_push에 해당 값의 인덱스를 지정합니다.

array_push($md_array['recipe_type'], $newdata);

오래된 주제인 건 알지만, 구글 검색하다가 우연히 발견해서...다음은 다른 해결 방법입니다.

$array_merged = array_merge($array_going_first, $array_going_second);

이건 꽤 깨끗해 보이는데, 잘 작동해요!

이 코드로 입수했습니다.코드는 매우 깨끗합니다.$array_display = array_display_going_first, $array_going_second).

언급URL : https://stackoverflow.com/questions/16308252/php-add-elements-to-multidimensional-array-with-array-push

반응형