PHP Array duplicate data count

292

I have title and language data in PHP Array. I need to display repeated title count. Please check below array format.

Array ( 
  [0] => Array ( [title] => My_title1 [language] => English ) 
  [1] => Array ( [title] => My_title1 [language] => English ) 
  [2] => Array ( [title] => My_title2 [language] => Japanese ) 
) 

I need to display data in following format.

Title      Language   Count
My_title1  English    2
My_title2  Japanese   1

I tried following code

$count = array_count_values(array_map(
function($item) {
    return $item['title'];
}, $testArray));
print_r($count);

but I got only title counts.

Array ( [My_title1] => 2 [My_title2] => 1  ) 

How do I display like following format?

Title      Language   Count
My_title1  English    2
My_title2  Japanese   1
46

Answer

Solution:

You can do it for example this way:

<?php

$testArray = array ( 
  0 => Array ( 'title' => 'My_title1', 'language' => 'English' ), 
  1 => Array ( 'title' => 'My_title1', 'language' => 'English' ), 
  2 => Array ( 'title' => 'My_title2', 'language' => 'Japanese' ), 
); 

$count = array_count_values(array_map(
function($item) {
    return $item['title'].'#'.$item['language'];
}, $testArray));

$outArray = array();

foreach ($count as $k => $v) {
    $k = explode('#', $k);
    $record['Title'] = $k[0];
    $record['Language'] = $k[1];
    $record['Count'] = $v;

    $outArray[] = $record;
}

var_dump($outArray);

Of course you need to use character that will not be used inside title and language, probably# is quite good enough

185

Answer

Solution:

Try this code code which i created just for this assignment

<?php
$array = array(
       0 => array ( 'title' => 'My_title1', 'language' => 'English'), 
       1 => array ( 'title' => 'My_title1', 'language' => 'English'), 
       2 => array ( 'title' => 'My_title2', 'language' => 'Japanese')

    );
    $final = array();

    foreach($array as $key =>$value)
    {
        $flag = 0;
        foreach($final as $key1 =>$value1)
        {

            if($array[$key]['title'] == $final[$key1]['title'])
            {
                $final[$key1]['count']++;
                $flag = 1;
            }

        }
        if($flag == 0)
        {
            $push = array('title' => $array[$key]['title'],'language' => $array[$key]['language'],'count' =>1);
            array_push($final,$push);
        }   
    }
echo "<pre>";print_r($final);

People are also looking for solutions to the problem: html - How to Call the one php page content and display it another php page using ajax

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.