以下是我的数组,我想检查条件并以有效的方式进行数组操作。哪个是,
resourceContext
是10
还是11
。 10
我希望替换数组的名称索引
这是自己的价值。
从"name" => "Agency FB Bold"
到"Agency FB Bold" => "/var/opt/nc/downloads/54007"
,fileReference
的值。这是因为resourceContext
的值为11
。 resourceContext
值为10
,则"Agency FB Bold"
的索引值应为pclFontNumber
的值,这将使"Agency FB Bold" => "54007"
$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 pop
和array previous
数组接下来`但无法正确使用。
答案 0 :(得分:1)
<?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
变量。这项技术使我们能够避免使用if
和elseif
。
这是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。