PHP将索引转换为新数组

时间:2017-12-19 22:43:40

标签: php

我有一个像下面这样的json数组。我需要将索引放入一个新数组,这怎么可能?阵列是我的弱点,出于某种原因只是无法掌握它们。我可以轻松获取id值,但无法获取索引(例如11111111)。任何帮助,将不胜感激。

更新请看修改后的,我的错误是不包括完整的多维数组。

下面只输出一个我需要所有结果的结果。

<?php

$json = '[{
    "11111111": {
        "id": "val_somevalue5555",
        "customer": {
            "32312": {
                "name": "jane doe"
            }
        }
    },
    "2222222": {
        "id": "val_somevalue25",
        "customer": {
            "32312234": {
                "name": "jane doe"
            }
        }
    }
}]';

$jsonarr = json_decode($json, true);

$newarr = [];

foreach($jsonarr as $value)
{
    $key = key($value);
    $newarr[] = ['key' => $key, 'id' => $value[$key]['id']];
}
var_dump($newarr);

    expected looped output 
    key 11111111 
    id val_somevalue5555
    ... looped.

6 个答案:

答案 0 :(得分:1)

您可以使用array_keys()函数

创建现有数组的键数组

http://php.net/manual/en/function.array-keys.php

如果您不希望键位于单独的数组中,而只是想直接访问它们,那么当您执行数组的'foreach'循环时,您可以选择通过以下方式将变量分配给当前键:做

foreach($jsonarr as $key => $value){...}  

因为你的原始数组实际上是多维的(每个$ key都有一个$值,也存储为“id”:“value”的数组) - 这意味着再多花一步来获取key'id'的值:

foreach($jsonarr as $key => $value){     
 $newarray[] = ['key' => $key, 'id' => $value['id'];
}

答案 1 :(得分:1)

您可以array_keys()key()使用foreach循环(DEMO):

$newarr = [];

foreach($jsonarr as $value)
{
    //$key = array_keys($value)[0];
    $key = key($value);
    $newarr[] = ['key' => $key, 'id' => $value[$key]['id']];
}
var_dump($newarr);

输出:

array(2) {
  [0]=>
  array(2) {
    ["key"]=>
    int(11111111)
    ["id"]=>
    string(17) "val_somevalue5555"
  }
  [1]=>
  array(2) {
    ["key"]=>
    int(2222222)
    ["id"]=>
    string(15) "val_somevalue25"
  }
}

编辑:使用更新的json,您可以使用以下方式,使用2个foreach循环(DEMO):

$newarr = [];

foreach($jsonarr as $json)
{
    foreach($json as $key => $value)
    {
        $newarr[] = ['key' => $key, 'id' => $value['id']];
    }
}

答案 2 :(得分:0)

PHP支持稍微不同的foreach语法,它提取数组键和数组值:

foreach ( $jsonarr as $key => $value ) {
    $newarr[] = ['key' => $key, 'id' => $value];
}

如果您需要密钥(在您的示例中为“11111111”和“2222222”),请使用此项。

答案 3 :(得分:0)

<?php
$json = '[{
    "11111111": {
        "id": "val_somevalue5555"
    }
},
{
    "2222222": {
        "id": "val_somevalue25"
    }
}
]';

$jsonarr = json_decode($json, true);

$newarr = [];
foreach($jsonarr as $key => $value) {
        $newarr[] = ['key' => key($value), 'id' => current($value)['id']];
}

foreach($newarr as $key) {
    echo 'key '.$key['key'] . PHP_EOL;
    echo 'id '.$key['id'] . PHP_EOL;
}

答案 4 :(得分:0)

如果删除$ json字符串中的嵌入式组件(否则它不会解析),那么var_export json_decode()的输出你将得到这个:

array (
   0 => array (
      11111111 => array (
          'id' => 'val_somevalue5555',
      ),
   ),
   1 => array (
      2222222 => array (
          'id' => 'val_somevalue25',
      ),
   ),
)

你有一个双嵌套数组,因此......

foreach ($jsonarr as $obj) {
   foreach ($obj as $name=>$value) {
      print "$name = $value[id]\n";
      break;
   }
}

或者您可以直接引用这些元素:

print $jsonarr[0]['11111111']['id'];

答案 5 :(得分:0)

首先,在迭代之前,你没有足够深入地访问。

如果您致电var_export($jsonarr);,您会看到:

array (                                 // an indexed array of subarrays
  0 =>
  array (                               // an associative array of subarrays, access via [0] syntax (or a foreach loop that only iterates once)
    11111111 =>                         // this is the subarray's key that you want
    array (
      'id' => 'val_somevalue5555',      // this is the value you seek from the id element of 1111111's subarray
      'customer' => 
      array (
        32312 => 
        array (
          'name' => 'jane doe',
        ),
      ),
    ),
    2222222 =>                         // this is the subarray's key that you want
    array (
      'id' => 'val_somevalue25',      // this is the value you seek from the id element of 2222222's subarray
      'customer' => 
      array (
        32312234 => 
        array (
          'name' => 'jane doe',
        ),
      ),
    ),
  ),
)

代码:(Demo

$jsonarr = json_decode($json, true);
$result=[];
//                     vvvv-avoid a function call (key()) on each iteration by declaring here
foreach($jsonarr[0] as $key=>$subarray){
    //          ^^^-drill down into the first level (use another foreach loop if there may be more than one)
    $result[]=['key'=>$key,'id'=>$subarray['id']];
}
var_export($result);

输出:

array (
  0 => 
  array (
    'key' => 11111111,
    'id' => 'val_somevalue5555',
  ),
  1 => 
  array (
    'key' => 2222222,
    'id' => 'val_somevalue25',
  ),
)

P.S。如果$jsonarr在第一级中有多个元素,则应使用foreach()这样的循环:

foreach($jsonarr as $array1){
    foreach($array1 as $key=>$array2){
        $result[]=['key'=>$key,'id'=>$array2['id']];
    }
}