Php 按键拆分和分组数组

Php 按键拆分和分组数组,php,arrays,grouping,Php,Arrays,Grouping,好的,我已经做了一些搜索,但还没有找到答案,所以我要尝试一下 我有一个JSON文件,可以输出以下信息: [ { "Contact name(s)": "Person 1, Person 2", "Contact title(s)": "Head Comacho, Other Guy", "Contact email(s)": "email1@email.net, email@email.com", "Contact phon

好的,我已经做了一些搜索,但还没有找到答案,所以我要尝试一下

我有一个JSON文件,可以输出以下信息:

[
    {
        "Contact name(s)": "Person 1, Person 2",
        "Contact title(s)": "Head Comacho, Other Guy",
        "Contact email(s)": "email1@email.net, email@email.com",
        "Contact phone": "123-456-7890, 789-456-1230",
    },
    {   
        "Contact name(s)": "Some Dude",
        "Contact title(s)": "Cool Title",
        "Contact email(s)": "things@email.com",
        "Contact phone": "555-555-5555",
    },
        "Contact name(s)": "",
        "Contact title(s)": "",
        "Contact email(s)": "",
        "Contact phone": "",
    }
]
不幸的是,这就是数据的命名方式。从我手中。无论如何,我必须得到它,这样这些有多个联系人的人将分组到他们自己的阵列中。以下是它需要的外观:

Array
(
    [0] => Array
        (
            [contact_name] => Person 1
            [contact_title] => Head Comacho
            [contact_email] => email1@email.net
            [contact_phone] => 123-456-7890
        )

    [1] => Array
        (
            [contact_name] => Person 2
            [contact_title] => Other Title
            [contact_email] => email@email.com
            [contact_phone] => 789-456-1230
        )
)
Array
(
    [0] => Array
        (
            [contact_name] => Some Dude
            [contact_title] => Cool Title
            [contact_email] => things@email.com
            [contact_phone] => 555-555-5555
        )
)
Array
(
    [0] => Array
        (
            [contact_name] => 
            [contact_title] => 
            [contact_email] => 
            [contact_phone] => 
        )
)
我能够将数据转换为它们自己的数组,如下所示:

Array
(
    [contact_name] => Array
        (
            [0] => Person 1
            [1] => Person 2
        )

    [contact_title] => Array
        (
            [0] => Head Comacho
            [1] => Other Guy
        )

    [contact_email] => Array
        (
            [0] => email1@email.net
            [1] => email@email.com
        )

    [contact_phone] => Array
        (
            [0] => 123-456-7890
            [1] => 789-456-1230
        )

)

Array
(
 .....etc
)
我如何才能像第一个例子那样得到它


道歉如果之前有人回答过,我不知道该如何回答我的问题。非常感谢您提供的所有帮助。

如果您可以确保多人的json对象始终包含相同数量的元素,那么您可以这样做:

<?php

$json = '[
    {"Contact name(s)": "Person 1, Person 2", "Contact title(s)": "Head Comacho, Other Guy", "Contact email(s)": "email1@email.net, email@email.com", "Contact phone": "123-456-7890, 789-456-1230"},
    {"Contact name(s)": "Some Dude", "Contact title(s)": "Cool Title", "Contact email(s)": "things@email.com", "Contact phone": "555-555-5555"},
    {"Contact name(s)": "", "Contact title(s)": "", "Contact email(s)": "", "Contact phone": ""}
]';

$jsonA = json_decode($json, true);

$result = [];
$maxLen = 0;
foreach ($jsonA as &$obj) {
    foreach ($obj as $k => $v) {
        if (!isset($result[$k])) $result[$k] = [];
        foreach (explode(',', $v) as $av) $result[$k][] = trim($av);
        $maxLen = max($maxLen, count($result[$k]));
    }
}

$objects = [];
for ($i=0; $i<$maxLen; $i++) {
    $object = [];
    foreach (array_keys($result) as $k) $object[$k] = isset($result[$k][$i]) ? $result[$k][$i] : '';
    $objects[] = $object;
}

echo '<pre>';
print_r($objects);

我想这个脚本可以满足你的要求。我已经创建了一个函数
split_contacts
,它获取解码数组中的每个条目,并将值(例如
“Person 1,Person 2”
=>[“Person 1”,“Person 2”])拆分成由对象键索引的数组,对象键由
preg_replace
按您想要的形式(例如
“Contact name(s)”=>“contact_name”
)。请注意,可以使用
str_replace
而不是
preg_replace
,但我希望在键值格式方面保持代码的灵活性

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [contact_name] => Person 1
                    [contact_title] => Head Comacho
                    [contact_email] => email1@email.net
                    [contact_phone] => 123-456-7890
                )    
            [1] => Array
                (
                    [contact_name] =>  Person 2
                    [contact_title] =>  Other Guy
                    [contact_email] =>  email@email.com
                    [contact_phone] =>  789-456-1230
                )    
        )    
    [1] => Array
        (
            [0] => Array
                (
                    [contact_name] => Some Dude
                    [contact_title] => Cool Title
                    [contact_email] => things@email.com
                    [contact_phone] => 555-555-5555
                )    
        )    
    [2] => Array
        (
            [0] => Array
                (
                    [contact_name] => 
                    [contact_title] => 
                    [contact_email] => 
                    [contact_phone] => 
                )    
        )    
)
输出:

$arr = '[
    {
        "Contact name(s)": "Person 1, Person 2",
        "Contact title(s)": "Head Comacho, Other Guy",
        "Contact email(s)": "email1@email.net, email@email.com",
        "Contact phone": "123-456-7890, 789-456-1230"
    },
    {   
        "Contact name(s)": "Some Dude",
        "Contact title(s)": "Cool Title",
        "Contact email(s)": "things@email.com",
        "Contact phone": "555-555-5555"
    },
    {
        "Contact name(s)": "",
        "Contact title(s)": "",
        "Contact email(s)": "",
        "Contact phone": ""
    }
]';

$arr = json_decode($arr, true);

foreach ($arr as $row) {

    list($m_name, $m_title, $m_email, $m_phone) =
    [explode(',', $row["Contact name(s)"]),explode(',', $row["Contact title(s)"]),
     explode(',', $row["Contact email(s)"]),explode(',', $row["Contact phone"])];

    foreach (array_keys($m_name) as $per)
        $result[] = ['name' => $m_name[$per],'title' => $m_title[$per],
                     'email' => $m_email[$per],'phone' => $m_phone[$per]];
}

var_dump($result);

我找到了这个解决方案:

$json = '[
    {"Contact name(s)": "Person 1, Person 2", "Contact title(s)": "Head Comacho, Other Guy", "Contact email(s)": "email1@email.net, email@email.com", "Contact phone": "123-456-7890, 789-456-1230"},
    {"Contact name(s)": "Some Dude", "Contact title(s)": "Cool Title", "Contact email(s)": "things@email.com", "Contact phone": "555-555-5555"},
    {"Contact name(s)": "", "Contact title(s)": "", "Contact email(s)": "", "Contact phone": ""}
]';
$array = json_decode($json, true);

$trans = [
    "Contact name(s)" => "contact_name",
    "Contact title(s)" => "contact_title",
    "Contact email(s)" => "contact_email",
    "Contact phone" => "contact_phone"    
];

foreach ($array as $set) {
    $temp = [];
    foreach ($set as $key => $data) {
        foreach (explode(', ', $data) as $index => $value) {
            $temp[$index][$trans[$key]] = $value;     
        }
    }
    $result[] = $temp;
}
var_export($result);

如果这是我的项目,这就是我要做的,为什么

  • 您需要将每个数据子集彼此分开,因此在外循环迭代之间使用
    $temp
    作为临时存储。必须在每个新的
    $set
    开始时重置临时数组,并且必须将临时数组数据传输到
    $result
    数组以维护原始的集合索引
  • explode()
    最好使用“逗号空间”作为分隔符参数——这样就不必调用任何附加函数来清除延迟的空间
  • 因为您的新旧密钥是已知的且是静态的,所以硬编码关联的“转换”数组将节省大量迭代函数调用,并在很大程度上减少代码膨胀。我还将指出,这使您能够更简单地控制密钥准备,未来的开发人员将能够很快理解您的代码在做什么
  • 代码:()

    输出:

    $arr = '[
        {
            "Contact name(s)": "Person 1, Person 2",
            "Contact title(s)": "Head Comacho, Other Guy",
            "Contact email(s)": "email1@email.net, email@email.com",
            "Contact phone": "123-456-7890, 789-456-1230"
        },
        {   
            "Contact name(s)": "Some Dude",
            "Contact title(s)": "Cool Title",
            "Contact email(s)": "things@email.com",
            "Contact phone": "555-555-5555"
        },
        {
            "Contact name(s)": "",
            "Contact title(s)": "",
            "Contact email(s)": "",
            "Contact phone": ""
        }
    ]';
    
    $arr = json_decode($arr, true);
    
    foreach ($arr as $row) {
    
        list($m_name, $m_title, $m_email, $m_phone) =
        [explode(',', $row["Contact name(s)"]),explode(',', $row["Contact title(s)"]),
         explode(',', $row["Contact email(s)"]),explode(',', $row["Contact phone"])];
    
        foreach (array_keys($m_name) as $per)
            $result[] = ['name' => $m_name[$per],'title' => $m_title[$per],
                         'email' => $m_email[$per],'phone' => $m_phone[$per]];
    }
    
    var_dump($result);
    

    您会发现这个解决方案不仅简洁、准确、易读;而且非常有效,因为整个过程中只有一个迭代函数调用(
    explode()
    )。

    您是否缺少一些字段?正如现在一样,JSON是无效的(最后一个字段上多了逗号,最后一个对象上缺少左括号).由于所提供的示例数据不需要regex,我宁愿看到更轻的调用:
    str_replace()
    @mickmackusa我试图保持代码的灵活性…我不知道OPs数据的其他部分是什么样的请对此代码的唯一答案添加一些解释,以提高其整体教育价值。@mickmackusa您的愿望…哦,等等,不,不是:-)。但这是一个公平的评论,肯定这个答案可以使用一些,我已经这样做了。
    $json = '[
        {"Contact name(s)": "Person 1, Person 2", "Contact title(s)": "Head Comacho, Other Guy", "Contact email(s)": "email1@email.net, email@email.com", "Contact phone": "123-456-7890, 789-456-1230"},
        {"Contact name(s)": "Some Dude", "Contact title(s)": "Cool Title", "Contact email(s)": "things@email.com", "Contact phone": "555-555-5555"},
        {"Contact name(s)": "", "Contact title(s)": "", "Contact email(s)": "", "Contact phone": ""}
    ]';
    $array = json_decode($json, true);
    
    $trans = [
        "Contact name(s)" => "contact_name",
        "Contact title(s)" => "contact_title",
        "Contact email(s)" => "contact_email",
        "Contact phone" => "contact_phone"    
    ];
    
    foreach ($array as $set) {
        $temp = [];
        foreach ($set as $key => $data) {
            foreach (explode(', ', $data) as $index => $value) {
                $temp[$index][$trans[$key]] = $value;     
            }
        }
        $result[] = $temp;
    }
    var_export($result);
    
    array (
      0 => 
      array (
        0 => 
        array (
          'contact_name' => 'Person 1',
          'contact_title' => 'Head Comacho',
          'contact_email' => 'email1@email.net',
          'contact_phone' => '123-456-7890',
        ),
        1 => 
        array (
          'contact_name' => 'Person 2',
          'contact_title' => 'Other Guy',
          'contact_email' => 'email@email.com',
          'contact_phone' => '789-456-1230',
        ),
      ),
      1 => 
      array (
        0 => 
        array (
          'contact_name' => 'Some Dude',
          'contact_title' => 'Cool Title',
          'contact_email' => 'things@email.com',
          'contact_phone' => '555-555-5555',
        ),
      ),
      2 => 
      array (
        0 => 
        array (
          'contact_name' => '',
          'contact_title' => '',
          'contact_email' => '',
          'contact_phone' => '',
        ),
      ),
    )