简体   繁体   English

将数组转换为关联 Object

[英]Convert Array to Associative Object

I want to convert:我想转换:

INPUT:输入:

array:3 [▼
  0 => {#476 ▼
    "click": 2412
    "ctr": 121
    "id": 12
    "trueview": 4124
    "view": 1452503
  }
  1 => {#478 ▼
    "click": 2222
    "ctr": 2222
    "id": 21
    "trueview": 2222
    "view": 2222
  }
  2 => {#1526 ▼
    "click": 3333
    "ctr": 3333
    "id": 31
    "trueview": 3333
    "view": 3333
  }
]

OUTPUT: OUTPUT:

{
  "12" : {
           "click": 2222,
           "trueview": 3333,
           "view": 3333,
           "ctr": 3333
         },
  "21" : {
           "click": 2222,
           "trueview": 3333,
           "view": 3333,
           "ctr": 3333
         },
  "31" : {
           "click": 2222,
           "trueview": 3333,
           "view": 3333,
           "ctr": 3333
         }
}

Loop the initial array and create a new array using the id as an index.循环初始数组并使用id作为索引创建一个新数组。 In code:在代码中:

$new_array = [];
foreach ($array as $key => $vals) {
    $id = $vals['id'];
    unset($vals['id']);
    $new_array[$id] = $vals;
}

var_dump($new_array);

Try this... you should get something... but you might need to make few changes depending upon your need试试这个......你应该得到一些东西......但你可能需要根据你的需要做一些改变

<?php
       

$arrays = array(
   0 =>  array(       
       "click" => 2412,
       "view" => 12456
       ),
   1=> array(
            "click"=> 2222,
            "ctr"=> 2222,
            "id"=> 21,
            "trueview"=> 2222,
            "view"=> 2222,
        )
);

echo "{\n";
foreach ($arrays as $index => $array)
{
    echo '"'.strval($index).'"'.":  {\n";
        
    foreach ($array as $key => $value)
    {
        echo '"'.($key).'":'.$value.",\n";
    }
    echo "\n\t},\n";
  
}

  echo "\n }";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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