简体   繁体   中英

PHP json_encode multidimensional array

I have an multidimensional array which looks like this:

array (size=6)
  'company' => 
    array (size=1)
      99 => string 'eeeeee'
  'Naam' => 
    array (size=1)
      1 => string 'werwerew'
  'phone' => 
    array (size=1)
      4 => string 'ewrwerwer'
  'email' => 
    array (size=1)
      3 => string 'test@test.com' 

Can I get json_encode output of this array something like this?

{"company":"eeeeee":"99","Naam":"werwerew":"1","phone":"ewrwerwer":"4","email":"test@test.com":"3","mesaj":"werewrewr":"0"}

Currently I json_encode the array and the output is this:

{"company":{"99":"eeeeee"},"Naam":{"1":"werwerew"},"phone":{"4":"ewrwerwer"},"email":{"3":"test@test.com"},"mesaj":{"0":"werewrewr"}}

and is not what I want.

The output you are looking for is not valid JSON. If your aim is to have a result that does not have nested braces, then first unnest your source array structure:

// sample data
$data = array (
  'company' => array("99" => 'eeeeee'),
  'Naam' => array ("1" => 'werwerew'),
  'phone' => array ("4" => 'ewrwerwer'),
  'email' =>  array ("3" => 'test@test.com')
);  

// unnest array, assuming inner level arrays only have one key/value pair:
foreach ($data as $key => $row) {
    $result[$key . ":" . current($row)] = "" . key($row);
}

// Now convert that flat array to JSON
$json = json_encode($result);

$json will have this value:

{"company:eeeeee":"99","Naam:werwerew":"1","phone:ewrwerwer":"4","email:test@test.com":"3"}

Note that this is valid JSON, as here the first colon is part of the key name.

If you prefer the numbers not to have double quotes around them, then remove the "" . part from the loop, to get this:

foreach ($data as $key => $row) {
    $result[$key . ":" . current($row)] = key($row);
}

$json will then get this value:

{"company:eeeeee":99,"Naam:werwerew":1,"phone:ewrwerwer":4,"email:test@test.com":3}

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