简体   繁体   中英

How to concatenate values using associative array in PHP?

I am using foreach loop and I want to display related value in separate array my current result is this:

{"response": {
    "message":"",
    "statistics": [
    {
        "player_name": "J. Bruun Larsen",
        "goals_total": "2"
    },
    {
        "player_name": "Ö. Toprak",
        "goals_total": "1"
    },

    {
        "player_name": "M. Hitz",
        "goals_assists": "0"
    },
    {
        "player_name": "M. Hitz",
        "goals_assists": "0"
    },

    {
        "player_name": "Ö. Toprak",
        "cards_yellow": "6"
    },
    {
        "player_name": "Ö. Toprak",
        "cards_yellow": "5"
    },

    {
        "player_name": "Ö. Toprak",
        "cards_red": "0"
    },
    {
        "player_name": "Ö. Toprak",
        "cards_red": "0"
    },
  ]}
}

I want to display each related value in its own array. example: the goals_total value in goals_total array and like this the goals_assist value in goal_assist array. I am using foreach loop in php.

You might use PHP core function called array_colum() which can direct return values of keys which exists in array.

    {
        "player_name": "M. Hitz",
        "goals_assists": "0"
    },
    {
        "player_name": "M. Hitz",
        "goals_assists": "0"
    },

    {
        "player_name": ". Toprak",
        "cards_yellow": "6"
    },
    {
        "player_name": ". Toprak",
        "cards_yellow": "5"
    },

    {
        "player_name": ". Toprak",
        "cards_red": "0"
    },
    {
        "player_name": ". Toprak",
        "cards_red": "0"
    }
  ]}
}',1);
$goals_total  = array_column($data['response']['statistics'],'goals_total');
$goals_assist  = array_column($data['response']['statistics'],'goals_assist');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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