通过按键值过滤我的数组结果来创建新数组

我有这个变量$office,它会在 print_r 时输出:


{

  "total": 3,

  "results": [

    {

      "id": "4",

      "blog_id": "11",

      "office_name": "Japan",

      "office_status": "inactive"

    },

    {

      "id": "5",

      "blog_id": "11",

      "office_name": "USA",

      "office_status": "active"

    },

    {

      "id": "6",

      "blog_id": "11",

      "office_name": "London",

      "office_status": "inactive"

    },

    }


}

现在我想创建一个新变量,其中带有office_statusof 的 变量active只会出现,我想要的输出是:


{

      "total": 1,

      "results": [

        {

          "id": "5",

          "blog_id": "11",

          "office_name": "",

          "office_status": "active"

        },

        }


    }

这是我到目前为止尝试过的,但它仍然返回所有数组:


$v= "active";

$k = "office_status";

foreach($offices as $k => $v) {

    $offices_active[$k] = array_filter($v);

}

print_r($offices_active);

请帮忙。谢谢


POPMUISE
浏览 82回答 2
2回答

MYYA

实际上它可以通过许多不同的方式来完成,一种方法就是这样做。<?php$object = '{"total":3,"results":[{"id":"4","blog_id":"11","office_name":"Japan","office_status":"inactive"},{"id":"5","blog_id":"11","office_name":"USA","office_status":"active"},{"id":"6","blog_id":"11","office_name":"London","office_status":"inactive"}]}';$offices = json_decode($object,true);$new = array_filter($offices['results'], function ($var) {&nbsp; &nbsp; return ($var['office_status'] == 'active');});$expected['total'] = count($new);$expected['results'] = $new;echo json_encode($expected);?>工作演示: https ://3v4l.org/NXZvQ

温温酱

此代码有助于通过状态值获取数据<?php$src_ar = '{"total":3,"results":[{"id":"4","blog_id":"11","office_name":"Japan","office_status":"inactive"},{"id":"5","blog_id":"11","office_name":"USA","office_status":"active"},{"id":"6","blog_id":"11","office_name":"London","office_status":"inactive"}]}';$office_info = json_decode($src_ar,true);$inactive_array = sort_by_office_status('inactive', $office_info['results']);print_r($inactive_array);$active_array = sort_by_office_status('active', $office_info['results']);print_r($active_array);function sort_by_office_status( $office_status, $result_array ) {&nbsp; &nbsp; $return_ar =array();&nbsp; &nbsp; if( !empty( $result_array ) ) {&nbsp; &nbsp; &nbsp; &nbsp; foreach( $result_array as $res ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if( $res['office_status'] == $office_status ) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $return_ar['results'][] = $res;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; $return_ar['results'] = array();&nbsp; &nbsp; }&nbsp; &nbsp; $result_count = count( $return_ar['results'] );&nbsp; &nbsp; $return_ar['total'] = $result_count;&nbsp; &nbsp; return $return_ar;}?>
打开App,查看更多内容
随时随地看视频慕课网APP