PHP构建了基于条件

时间:2017-05-12 10:14:37

标签: php arrays conditional-statements

以下是我的数组,我想检查条件并以有效的方式进行数组操作。哪个是,

  1. 我必须检查以下数组中的resourceContext10还是11
  2. 如果是10我希望替换数组的名称索引 这是自己的价值。 从"name" => "Agency FB Bold""Agency FB Bold" => "/var/opt/nc/downloads/54007"fileReference的值。这是因为resourceContext的值为11
  3. 如果resourceContext值为10,则"Agency FB Bold"的索引值应为pclFontNumber的值,这将使"Agency FB Bold" => "54007"
  4. $gAllFonts = array("mFontList" => array(array("name" => "Agency FB Bold", "pclFontNumber" => "54007", "fontType" => "0", "fileReference" => "/var/opt/nc/downloads/54007", "resourceContext" => "11"), array("name" => "Albertus Extra Bold", "pclFontNumber" => "53056", "fontType" => "0", "fileReference" => "/var/opt/nc/downloads/53056", "resourceContext" => "10"), array("name" => "Albertus Medium", "pclFontNumber" => "53041", "fontType" => "0", "fileReference" => "/var/opt/nc/downloads/53041", "resourceContext" => "10"), array("name" => "Antique Olive", "pclFontNumber" => "52795", "fontType" => "0", "fileReference" => "/var/opt/nc/downloads/52795", "resourceContext" => "10")));

    如何使用PHP内置方法完成此操作?

    我尝试使用array poparray previous数组接下来`但无法正确使用。

2 个答案:

答案 0 :(得分:1)

Try this code snippet here

<?php
ini_set('display_errors', 1);
$result=array();
$gAllFonts = array("mFontList" => array(array("name" => "Agency FB Bold", "pclFontNumber" => "54007", "fontType" => "0", "fileReference" => "/var/opt/nc/downloads/54007", "resourceContext" => "11"), array("name" => "Albertus Extra Bold", "pclFontNumber" => "53056", "fontType" => "0", "fileReference" => "/var/opt/nc/downloads/53056", "resourceContext" => "10"), array("name" => "Albertus Medium", "pclFontNumber" => "53041", "fontType" => "0", "fileReference" => "/var/opt/nc/downloads/53041", "resourceContext" => "10"), array("name" => "Antique Olive", "pclFontNumber" => "52795", "fontType" => "0", "fileReference" => "/var/opt/nc/downloads/52795", "resourceContext" => "10")));
foreach ($gAllFonts["mFontList"] as $key => $value)
{
    if ($value["resourceContext"] == 11)
    {
        $result["mFontList"][][$value["name"]]= $value["fileReference"];
    }
    elseif ($value["resourceContext"] == 10)
    {
        $result["mFontList"][][$value["name"]]= $value["pclFontNumber"];
    }
}
print_r($result);

答案 1 :(得分:1)

您可以使用array_map

$mapping = [
    '10' => 'pclFontNumber',
    '11' => 'fileReference'
];

$gAllFonts['mFontList'] = array_map(function ($font) use ($mapping) {
    if (isset($mapping[$font['resourceContext']])) {
        $font[$font['name']] = $font[$mapping[$font['resourceContext']]];
    }

    return $font;
}, $gAllFonts['mFontList']);

注意$mapping变量。这项技术使我们能够避免使用ifelseif

这是working demo

修改

如果您需要完全替换数组:

$mapping = [
    '10' => 'pclFontNumber',
    '11' => 'fileReference'
];

$gAllFonts['mFontList'] = array_map(function ($font) use ($mapping) {
    return [
        $font['name'] => $font[$mapping[$font['resourceContext']]]
    ];
}, $gAllFonts['mFontList']);

这是working demo