用字符串替换PHP嵌套/多维数组的数字键

时间:2018-06-20 16:24:22

标签: php arrays multidimensional-array nested

我有一个像这样的数组-它是通过​​Wordpress通过动态if / while循环生成的

<?php $qry = new WP_Query($args); if ($qry->have_posts()) : 
$count = 0; 
$arr = array(); 
while ($qry->have_posts()) : $qry->the_post(); $count++;
$thetitle = get_the_title();
$arr[$count] = array("name" => $thetitle);?>
<?php if( have_rows('product_attributes') ): ?>
<?php while( have_rows('product_attributes') ): the_row();  ?>
<?php array_push($arr[$count], get_sub_field('text'));?>
<?php endwhile; endif; ?>     
<?php endwhile; endif ?>
<?php print_r($arr); ?>

结果

Array ( [1] => Array ( [name] => Breakfast Cereal [0] => 92.50% [1] => 11.00% [2] => 14.0 MJ/kg [3] => 10.00% [4] => 7.50% [5] => 1.80% ) )

在使用<?php $json_out = json_encode(array_values($arr)); ?>转换为json并删除数组的键之后。

<?php $json_out = json_encode(array_values($arr)); ?>
<?php echo $json_out; ?>`

结果

[{"name":"Breakfast Cereal","0":"92.50%","1":"11.00%","2":"14.0 MJ\/kg","3":"10.00%","4":"7.50%","5":"1.80%"}]

如何用字符串替换嵌套数组中的数字键-这些字符串将为get_sub_field('title')

1 个答案:

答案 0 :(得分:0)

$sJson = '[{"name":"Breakfast Cereal","0":"92.50%","1":"11.00%","2":"14.0 MJ\/kg","3":"10.00%","4":"7.50%","5":"1.80%"}]';
$aNamesForKeys = [0 => "Some", 1 => "Random", 2 => "Name"];
$aData = get_object_vars(json_decode($sJson)[0]);

foreach ($aData as $key => $value) {
    if (isset($aNamesForKeys[$key])) {
        $aData[$aNamesForKeys[$key]] = $value;
        unset($aData[$key]);
    }
}

var_dump($aData);

输出

array(7) {
  ["name"]=>
  string(16) "Breakfast Cereal"
  [3]=>
  string(6) "10.00%"
  [4]=>
  string(5) "7.50%"
  [5]=>
  string(5) "1.80%"
  ["Some"]=>
  string(6) "92.50%"
  ["Random"]=>
  string(6) "11.00%"
  ["Name"]=>
  string(10) "14.0 MJ/kg"
}

小心可能发生的按键碰撞!