简体   繁体   中英

How to create a 2 dimensional array from an associative array in php

i need to convert a associative array to a 2 dimensional array in php, the origin array is as followed

    array:7 [▼
  "data" => "data"
  "id_1553539135251" => "<p>nsmn</p>"
  "about" => "about"
  "id_1553539141598" => "<p>uiu</p>"

my code

        $data = $request->all();
        $json = array();
        foreach($data as $key => $value){

            if(strpos($key, 'id') !== false){
                $json[$key]['content'] = $value;
            }
        }

i need the output of the following for each to be

array:3 [▼
  "id_1553539135251" => array:1 [▼
    "content" => "<p>nsmn</p>"
    "data" => "data"
]
  "id_1553539141598" => array:1 [▼
    "content" => "<p>uiu</p>"
    "about" => "about"
  ]
]

but my code outputs

array:3 [▼
  "id_1553539135251" => array:1 [▼
    "content" => "<p>nsmn</p>"
  ]
  "id_1553539138029" => array:1 [▼
    "content" => "<p>jjkjk</p>"
  ]
  "id_1553539141598" => array:1 [▼
    "content" => "<p>uiu</p>"
  ]
]

guidance on how to achieve the desired output is appreciated.

 <?php $test=array( array( "data" => "data", "id_1553539135251" => "<p>nsmn</p>", "about" => "about", "id_1553539141598" => "<p>uiu</p>" ), ); $output=array(); foreach($test as $item){ $i=0; $tt=''; foreach($item as $k=>$v){ if(strpos($k, 'id') !== false){ $output[$k]=array( 'content'=>$item[$k], 'header'=>$tt, ); }else{ $tt=$v; } } } print_r($output); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM