Reputation: 7839
I have set of data that I need help with. I need to make a difficult calculation and array sort through several multidimensional arrays and the logic and syntax is giving me a headache.
Basically what I need it:
I know how I am going to do the calculation for the relevancy now, it's just I've only briefly worked with single dimension arrays and I don't know how to syntactically represent what I need with this example. Could anyone give me a hand?
Here is a sample of what I want - not sure if this is syntactically the best way to show you, but hopefully you'll get the picture:
Array
(
[Keywords] => Array
(
["wax"] => Array
(
[ID] => 1
[Match] => 8
[ID] => 2
[Match] => 10
)
["hard"] => Array
(
[ID] => 1
[Match] => 2
[ID] => 2
[Match] => 37
)
)
Then this array would need to be translated to:
Array
(
[ID] => Array
(
["1"] => Array
(
[Keyword] => "wax"
[Match] => 8
[Keyword] => "hard"
[Match] => 10
)
["2"] => Array
(
[Keyword] => "wax"
[Match] => 2
[Keyword] => "hard"
[Match] => 37
)
)
Upvotes: 0
Views: 430
Reputation: 17817
This code:
$arr = array
(
"wax" => array
(
array(
'ID' => 11,
'Match' => 8
),
array(
'ID' => 21,
'Match' => 10
)
),
"hard" => array
(
array(
'ID' => 11,
'Match' => 2
),
array(
'ID' => 21,
'Match' => 37
)
)
);
$byid = array();
foreach($arr as $kw => $res) {
foreach($res as $r) {
$byid[$r['ID']][] = array('Keyword' => $kw, 'Match' => $r['Match']);
}
}
var_export($byid);
gives:
array (
11 =>
array (
0 =>
array (
'Keyword' => 'wax',
'Match' => 8,
),
1 =>
array (
'Keyword' => 'hard',
'Match' => 2,
),
),
21 =>
array (
0 =>
array (
'Keyword' => 'wax',
'Match' => 10,
),
1 =>
array (
'Keyword' => 'hard',
'Match' => 37,
),
),
)
I hope it helps.
Upvotes: 1
Reputation: 1118
You can query the db and create both the arrays by,
$query = "select id, keyword, count(*) as keyword_count from [your table] group by keyword";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$keyword = $row['keyword'];
$id = $row['id'];
$count = $row['keyword_count'];
$first_array["keywords"]["$keyword"] = array('id' => $id, 'match' => $count);
$second_array["id"]["$id"] = array('keyword' => $keyword, 'match' => $count);
}
print_r($first_array);
print_r($second_array);
Upvotes: 0