如何减少数组嵌套

发布于 2024-12-17 16:40:10 字数 914 浏览 0 评论 0原文

基本上我的数组嵌套得太深了。它有三个子、子、子数组,我只想保留中间的一个。

我发现很难解释它,但我所拥有的是这样的:

"data": [
  {
  "order": 
      {
        "id": "1,", 
        "mail": {
        "mail1": "X";
        "mail2": "X";
         },
      },
      {
        "id": "2,", 
        "amount": "X", 
      },
   }
 ],
 "data": [
   {
  "order": {
        "id": "3,", 
        "amount": "X", 
      },
    }
 ],

我需要删除第一个和最后一个子数组,所以我只得到一个巢:

     [1] {
        "id": "[email protected],", 
        "mail1": "X", 
        "mail2": "X", 
      },
     [2] {
        "id": "2,", 
        "amount": "X", 
      },
     [3] {
        "id": "3,", 
        "amount": "X", 
      },

我不知道这是否有意义。我确信这不是很难做到的,但我只设法创建了一个 foreach 来创建一个包含所有值的数组,但我丢失了所有子数组。

这是怎么做到的? (至少删除第一个数组)。

Basically my array is nested too deep. It has three sub,sub,sub arrays and I only want to keep the middle one.

I find it hard to explain it but what I have is this:

"data": [
  {
  "order": 
      {
        "id": "1,", 
        "mail": {
        "mail1": "X";
        "mail2": "X";
         },
      },
      {
        "id": "2,", 
        "amount": "X", 
      },
   }
 ],
 "data": [
   {
  "order": {
        "id": "3,", 
        "amount": "X", 
      },
    }
 ],

I need to remove the first and last sub-arrays so I only get only one nest:

     [1] {
        "id": "[email protected],", 
        "mail1": "X", 
        "mail2": "X", 
      },
     [2] {
        "id": "2,", 
        "amount": "X", 
      },
     [3] {
        "id": "3,", 
        "amount": "X", 
      },

I don't know if this make sense. I'm sure this is not very difficult to do, but I only managed to make a foreach that creates an array with all values, but I lose all sub arrays.

How is this done? (at least removing the first array).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

落墨 2024-12-24 16:40:10

您的数组结构仍然无效,所以我不能肯定地说,但应该这样做:

$result = array();
foreach ($array['data'] as $order) {
    $order = $order['order'];
    if (isset($order['mail'])) {
        $order = array_merge($order, $order['mail']);
        unset($order['mail']);
    }
    $result[] = $order;
}

Your array structure is still invalid so I can't say for sure, but something along these lines should do:

$result = array();
foreach ($array['data'] as $order) {
    $order = $order['order'];
    if (isset($order['mail'])) {
        $order = array_merge($order, $order['mail']);
        unset($order['mail']);
    }
    $result[] = $order;
}
梦途 2024-12-24 16:40:10

试试这个:

$finalArr = array();
foreach($data as $key => $val) {
  array_push($finalArr, $val);
}
print_r($finalArr);

希望有帮助

Try this:

$finalArr = array();
foreach($data as $key => $val) {
  array_push($finalArr, $val);
}
print_r($finalArr);

Hope it helps

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文