【问题标题】:PHP : how to split Inside arrayPHP:如何拆分内部数组
【发布时间】:2022-01-17 18:57:37
【问题描述】:
Array
(
    [1] => dani : developer
    [2] => john : not_developer
)

我想在":" 拆分这个数组,并在每个地方创建另一个数组。

预期输出:

Array
    (
        [1] => array(
               "name" => "dani",
               "value" => "developer"
               )
        [2] => array(
               "name" => "john",
               "value" => "not_developer"
               )
     )

我尝试过使用explode(":", $attribute);,但爆炸无法在数组上工作。

【问题讨论】:

  • 使用foreach 循环并分解每个元素。

标签: php arrays


【解决方案1】:

使用 array_map 和自定义回调,将原始映射到您想要的:

<?php

$original =[
    'dani : developer',
    'john : not_developer',
];

$converted = array_map(
    function ($element) {
        list($name, $value) = explode(':', $element);

        return [
            'name' => trim($name),
            'value' => trim($value),
        ];
    },
    $original
);

var_dump($converted);

您可以再次使用这种使用array_map 的变体来一起进行爆炸和修剪:

<?php

$original =[
    'dani : developer',
    'john : not_developer',
];

$converted = array_map(
    function ($element) {
        list($name, $value) = array_map(
            'trim',
            explode(':', $element)
        );

        return [
            'name' => $name,
            'value' => $value,
        ];
    },
    $original
);

var_dump($converted);

或者这种变体进一步使用了所需输出的子键名的预设数组,以及array_combine

<?php

$original =[
    'dani : developer',
    'john : not_developer',
];

$conversion_keys = ['name', 'value'];

$converted = array_map(
    function ($element) use ($conversion_keys) {
        return array_combine(
            $conversion_keys,
            array_map(
                'trim',
                explode(':', $element)
            )
        );
    },
    $original
);

var_dump($converted);

他们都输出你想要的结果:

array(2) {
  [0]=>
  array(2) {
    ["name"]=>
    string(4) "dani"
    ["value"]=>
    string(9) "developer"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(4) "john"
    ["value"]=>
    string(13) "not_developer"
  }
}

【讨论】:

    【解决方案2】:
    $attributes_array = array();
        foreach( $hebrew_attributes_array as $attribute ){
            $attribute_array = explode(":", $attribute);
            $attributes_array[] = Array(
                                        "attribute_name" =>  $attribute_array[0],
                                        "attribute_value" => $attribute_array[1] 
                                        );
        }
        // $hebrew_string = explode(":", $hebrew_string);
        return $attributes_array;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      • 2013-08-09
      相关资源
      最近更新 更多