简体   繁体   English

从php中的字符串命名键值构建多维数组

[英]Build multidimensional array from string naming key values in php

So I have this problem, I am extracting a string from excel that has this structure:所以我遇到了这个问题,我正在从具有这种结构的 excel 中提取一个字符串:

89.356 87.54, 45.34 98.254, 45.2413 45.2146, 98.23 35.647 89.356 87.54、45.34 98.254、45.2413 45.2146、98.23 35.647

And I want to build an array with the following structure:我想构建一个具有以下结构的数组:

Array
(
    [0] => Array
        (
            ['first'] => 89.356 
            ['second'] => 87.54
        )

    [1] => Array
        (
            ['first'] => 45.34 
            ['second'] => 98.254
        )

    [2] => Array
        (
            ['first'] => 45.2413
            ['second'] => 45.2146
        )
)

I am extracting these values from an excel and creating the array like this:我从 excel 中提取这些值并创建这样的数组:

$polygons = $sheet->getCell("B".$row)->getValue();
        $ret = array_map (
            function ($) {return explode (' ', $);},
            explode (',', $polygons)
        );

But I do not know how to assign the key values 'first' and 'second' to the array.但我不知道如何将键值 'first' 和 'second' 分配给数组。

First of all, just to point out that your code will produce an error because you can't create a variable without a name ex.首先,只是指出您的代码会产生错误,因为您无法创建没有名称 ex 的变量。 in your code you only have $ as variable.在您的代码中,您只有$作为变量。

Here's how you do it.这是你如何做到的。

$ret = array_map( function( $pol ) {
    $a = array_map( 'floatval', explode( ' ', $pol, 2 ) ); // 1

    return array_combine( ['first', 'second'], $a ); // 2
}, explode( ',', $polygons ) );
  1. Convert from string to float.从字符串转换为浮点数。
  2. Assign the first array (['first', 'second']) as key to the second array将第一个数组 (['first', 'second']) 作为第二个数组的键

Output: var_dump( $ret );输出: var_dump( $ret );

array(3) {
    [0] => array(2) {
        ["first"] => float(89.356),
        ["second"] => float(89.356),
    },
    [1] => array(2) {
        ["first"] => float(45.34),
        ["second"] => float(98.254),
    },
    [2] => array(2) {
        ["first"] => float(45.2413),
        ["second"] => float(45.2146,
    },
}

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

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