更改php数组格式 [英] change php array format

查看:54
本文介绍了更改php数组格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面提到的数组,我的值将始终是3的倍数.

I have array mentioned below, I will have value always multiple of 3.

$xyz = array(array('name'=>'abc'),array("name"=>"snds"),array("name"=>""),array("number"=>"452"),array("number"=>"845120"),array("number" => "84514513200"),array("email" => "ddddf"),array("email" => "dkskns"),array("email" => "kjnksdnkds"));

但这不是我执行进一步操作的正确格式,因此我希望此数组如下所述.

but this is not the proper format for me to perform further operations, so I want this array like mentioned below.

$abc = array(array("name"=>"abc","number"=>'452',"email" => "ddddf"),array("name" => "snds","number" =>"845120","email" => "dkskns"),array("name" => "", "number" => "84514513200","email" => "kjnksdnkds"));

注意:数组长度是动态的,但始终是3的倍数

note: the array length is dynamic but it will always be multiple of 3

推荐答案

一种可能是使用取模 %运算符.

One possibility could be to use the modulo % operator.

foreach中,该值是一个数组,您可以使用 array_keys 获取密钥,然后重置以获取密钥的值.第一个数组元素.

In the foreach the value is an array and you could use array_keys to get the key and reset to get the value of the first array element.

$result = [];
$count = 0;
foreach ($xyz as $value) {
    if ($count%3 === 0) {
        $count = 0;
    }
    $result[$count][array_keys($value)[0]] = reset($value);
    $count++;
}

演示

这将为您提供:

array(3) {
  [0]=>
  array(3) {
    ["name"]=>
    string(3) "abc"
    ["number"]=>
    string(3) "452"
    ["email"]=>
    string(5) "ddddf"
  }
  [1]=>
  array(3) {
    ["name"]=>
    string(4) "snds"
    ["number"]=>
    string(6) "845120"
    ["email"]=>
    string(6) "dkskns"
  }
  [2]=>
  array(3) {
    ["name"]=>
    string(0) ""
    ["number"]=>
    string(11) "84514513200"
    ["email"]=>
    string(10) "kjnksdnkds"
  }
}

这篇关于更改php数组格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆