Jump to content

[SOLVED] Question about arrays - Advanced


Ninjakreborn

Recommended Posts

I have an array with 10 items.  Each one fo those items contains a master item and a subarray of subitems. I need to loop through EACH of the 10 arrays through all of the sub items and find out how many matches there are alike. So if sub item abc appears in array 1, and array 4 then I need to list out they were found 2 times.  It's wierd. i am guessing I need to create a matching algorithm for the arrays.  Where should I start?

Link to comment
https://forums.phpfreaks.com/topic/167634-solved-question-about-arrays-advanced/
Share on other sites

Something like this?

 

<?php
$array = array(
array(
	'foo',
	'bar',
),
array(
	'foo',
	'bar',
	'baz',
),
array(
	'foo',
	'baz',
),
);

// foo = 3
// bar = 2
// baz = 2

$count = array();
foreach ($array as $items) {
foreach ($items as $item) {
	if (!isset($count[$item])) {
		$count[$item] = 1;
	}
	else {
		$count[$item]++;
	}
}
}

print_r($count);

 

Output:

Array
(
    [foo] => 3
    [bar] => 2
    [baz] => 2
)

Very similiar. I ended up working up something simple to avoid the problem, so I got that situated.

The next question I have is how to sort an array based on the number of values that array has.

So let's say I have a big array.

 

bigarray['a']['a'] = 'test'

bigarray['a']['b'] = 'test'

bigarray['a']['c'] = 'test'

bigarray['b']['a'] = 'test'

bigarray['b']['b'] = 'test'

bigarray['c']['a'] = 'test'

 

I don't know what order that array would be in so I want to sort it so I can see the ones with the "most" values

first.  bigarray['a'] would be first then bigarray['b'] then bigarray['c']

 

I have a huge array and they are similiar, I just want to order the primary array based off the amount of each values. So if bigarray[c] had more values than a it would appear first. Then I will be listing them out based off how many values were in each array. Does that make sense?

 

Any advice?

<?php
array_multisort($bigarray, SORT_DESC);
?>

 

Just a simple multisort will do the job.

 

<?php
$bigarray['a']['a'] = 'test';
$bigarray['a']['b'] = 'test';
$bigarray['b']['a'] = 'test';
$bigarray['b']['b'] = 'test';
$bigarray['b']['c'] = 'test';
$bigarray['c']['a'] = 'test';

array_multisort($bigarray, SORT_DESC);

var_dump($bigarray);
?>

 

array(3) { ["b"]=>  array(3) { ["a"]=>  string(4) "test" ["b"]=>  string(4) "test" ["c"]=>  string(4) "test" } ["a"]=>  array(2) { ["a"]=>  string(4) "test" ["b"]=>  string(4) "test" } ["c"]=>  array(1) { ["a"]=>  string(4) "test" } }

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.