Merge duplicate keys in multi-dimensional array - php

I have a script that loops through a bunch of data collected from database tables. I've read other similar posts on StackOverflow about merging duplicate array keys, but none of them seem to work for me. Using the code below, I'm building all of the compiled data into an array:
$sql = 'SELECT * FROM '.$qstTable.' WHERE '.$type.'_qst_id = '.$answer['answer_qst'];
$result = $db->sql_query($sql);
$q = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
$sql = 'SELECT * FROM '.$catTable.' WHERE '.$type.'_cat_clean = "'.$q[$type.'_qst_cat'].'"';
$result = $db->sql_query($sql);
$cat = $db->sql_fetchrow($result);
$db->sql_freeresult($result);
$daField = $cat[$type.'_cat_name'];
if(count($allQsts)){
if(array_key_exists($daField, $allQsts)){
$daData = array(
'question' => array(
'id' => $q[$type.'_qst_id'],
'qst' => $q[$type.'_qst_qst'],
),
'answer' => array(
'id' => $answer['answer_id'],
'type' => $answer['answer_input'],
'content' => $answer['answer_content'],
'q_type' => $type,
)
);
array_push($allQsts[$daField], $daData);
}else{
$allQsts[$cat[$type.'_cat_name']][] = array(
'question' => array(
'id' => $q[$type.'_qst_id'],
'qst' => $q[$type.'_qst_qst'],
),
'answer' => array(
'id' => $answer['answer_id'],
'type' => $answer['answer_input'],
'content' => $answer['answer_content'],
'q_type' => $type,
)
);
}
}else{
$allQsts[$cat[$type.'_cat_name']][] = array(
'question' => array(
'id' => $q[$type.'_qst_id'],
'qst' => $q[$type.'_qst_qst'],
),
'answer' => array(
'id' => $answer['answer_id'],
'type' => $answer['answer_input'],
'content' => $answer['answer_content'],
'q_type' => $type,
)
);
}
And this is how my array turns out looking when it's all processed:
Array (
[Ancestry] => Array (
[0] => Array (
[question] => Array (
[id] => 1
[qst] => Has your family always lived in this country? Where did your family come from? How did they come here?
)
[answer] => Array (
[id] => 28
[type] => text
[content] => idk
[q_type] => life
)
)
)
)
Array (
[High School] => Array (
[0] => Array (
[question] => Array (
[id] => 158
[qst] => Who were your best friends in high school? Were they the same ones from grade school? Do you still keep in touch with them?
)
[answer] => Array (
[id] => 30
[type] => video
[content] => v-0bd3d270-2f24-0132-cd89-12313914f10b
[q_type] => life
)
)
)
)
Array (
[High School] => Array (
[0] => Array (
[question] => Array (
[id] => 124
[qst] => What year did you start high school? What high school did you go to? Did you like it? Did you ever wish you would've gone to a different high school?
)
[answer] => Array (
[id] => 36
[type] => text
[content] => Started HS in 1987
[q_type] => life
)
)
)
)
Array (
[Young Adult] => Array (
[0] => Array (
[question] => Array (
[id] => 213
[qst] => As a young adult did you stay in the same town as your friends or did you move to a new place and had to make new friends?
)
[answer] => Array (
[id] => 39
[type] => video
[content] => v-7d59df50-3bda-0132-cda7-12313914f10b
[q_type] => life
)
)
)
)
Array (
[Young Adult] => Array (
[0] => Array (
[question] => Array (
[id] => 207
[qst] => After high school - did you go to college, join the miltary, or did you get a job?
)
[answer] => Array (
[id] => 40
[type] => text
[content] => went to college at ASU
[q_type] => life
)
)
)
)
Array (
[Multiple Sclerosis] => Array (
[0] => Array (
[question] => Array (
[id] => 1278
[qst] => Do you know of any potential new drugs or treatments that are in development to treat multiple sclerosis? Are you optomistic?
)
[answer] => Array (
[id] => 33
[type] => text
[content] => vg hjc
[q_type] => pack
)
)
)
)
However, What I would like to do is combine nodes in the array that already exist, like so:
Array (
[Ancestry] => Array (
[0] => Array (
[question] => Array (
[id] => 1
[qst] => Has your family always lived in this country? Where did your family come from? How did they come here?
)
[answer] => Array (
[id] => 28
[type] => text
[content] => idk
[q_type] => life
)
)
)
)
Array (
[High School] => Array (
[0] => Array (
[question] => Array (
[id] => 158
[qst] => Who were your best friends in high school? Were they the same ones from grade school? Do you still keep in touch with them?
)
[answer] => Array (
[id] => 30
[type] => video
[content] => v-0bd3d270-2f24-0132-cd89-12313914f10b
[q_type] => life
)
)
[1] => Array (
[question] => Array (
[id] => 124
[qst] => What year did you start high school? What high school did you go to? Did you like it? Did you ever wish you would've gone to a different high school?
)
[answer] => Array (
[id] => 36
[type] => text
[content] => Started HS in 1987
[q_type] => life
)
)
)
)
Array (
[Young Adult] => Array (
[0] => Array (
[question] => Array (
[id] => 213
[qst] => As a young adult did you stay in the same town as your friends or did you move to a new place and had to make new friends?
)
[answer] => Array (
[id] => 39
[type] => video
[content] => v-7d59df50-3bda-0132-cda7-12313914f10b
[q_type] => life
)
)
[1] => Array (
[question] => Array (
[id] => 207
[qst] => After high school - did you go to college, join the miltary, or did you get a job?
)
[answer] => Array (
[id] => 40
[type] => text
[content] => went to college at ASU
[q_type] => life
)
)
)
)
Array (
[Multiple Sclerosis] => Array (
[0] => Array (
[question] => Array (
[id] => 1278
[qst] => Do you know of any potential new drugs or treatments that are in development to treat multiple sclerosis? Are you optomistic?
)
[answer] => Array (
[id] => 33
[type] => text
[content] => vg hjc
[q_type] => pack
)
)
)
)
How can I modify the code above to do this?
EDIT - Updating to include some of the code I've tried to compress the array:
After the full $allQsts array is created, I looped it through this and tested the output, but each entry was duplicated even more.
$sortedIt = array();
foreach($allQsts as $m => $n){
if(!isset($sortedIt[$m])){
$sortedIt[$m] = array();
}
$sortedIt[$m] = $n;
}
I've also been playing around with array_merge_recursive but have yet to get anywhere close.

Assuming this is run in a loop and $allQsts points to the same array each time, you can simplify the code drastically:
$daField = $cat[$type.'_cat_name'];
$daData = array(
'question' => array(
'id' => $q[$type.'_qst_id'],
'qst' => $q[$type.'_qst_qst'],
),
'answer' => array(
'id' => $answer['answer_id'],
'type' => $answer['answer_input'],
'content' => $answer['answer_content'],
'q_type' => $type,
)
);
if (array_key_exists($daField, $allQsts)) {
$allQsts[$daField][] = $daData;
} else {
$allQsts[$daField] = array($daData);
}
This by itself should be enough to get the desired data structure.

Related

Array PHP, Check if exist multiple elements to another array

I have a question about this:
I have two array, one is static, and one can be updated by the user...
I would like to check for every id from the static array if exist the id to the other array, and if exsist, do something, if doesn't exist (when finish to check) pass to other ID etc...
now, the arrays are these:
user array (the user unlock 2 achievement):
Array (
[0] => Array (
[data] => Array (
[importance] => 0
[achievement] => Array (
[id] => 644081262362202
[title] => Achievement 2
[type] => game.achievement
[url] => http://www.***.com/achievements/achievement2.html
)
)
[id] => 104693166566570
)
[1] => Array (
[data] => Array (
[importance] => 0
[achievement] => Array (
[id] => 968802826528055
[title] => Achievement 1
[type] => game.achievement
[url] => http://www.***.com/achievements/achievement1.html
)
)
[id] => 104023386633548
)
)
the static Array (have 6 achievement saved):
Array (
[0] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement2
[title] => Achievement 2
[id] => 644081262362202
)
[1] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement3
[title] => Achievement 3
[id] => 912599152147444
)
[2] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement5
[title] => Achievement 5
[id] => 913757345379232
)
[3] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement6
[title] => Achievement 6
[id] => 921989084564878
)
[4] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement1
[title] => Achievement 1
[id] => 968802826528055
)
[5] => Array (
[data] => Array (
[points] => 50
)
[description] => you unlock the achievement4
[title] => Achievement 4
[id] => 1149671038394021
)
)
now, I use this script to echo the final output like the picture (results is the static array):
if (empty($results)) {
//echo 'noAchievement for the app';
} else {
foreach ($results as $result) {
$totalAchievementsApp .= ' [["' . "0" .'"],["'.$result[id] .'"],["'. $result[title] .'"],["'. $result[data][points]."]] ";
}
}
now, How I can do to check inside the this script? I know I have to add another if inside the else to check if the ID is = to other ID, but I don't know how, I'm a little bit confused... I would like to check if the id of the static array exist in the other array, and if exsist, do this:
**$totalAchievementsApp .= ' [["' . "1" .'"],["'.$result[id] .'"],["'. $result[title] .'"],["'. $result[data][points]."]] ";**
Thank you very much :)
If I understand correctly, you want to indicate for each entry in the static array whether its ID exists in the user array.
You can use array_column to generate an array of all IDs in the user array. Then use in_array to check if each static ID exists in that array. Set a value to 1 if its found and 0 if its not found.
For the sake of example, I've generated a new final output array. But you could just add the "found" value to each entry of the the static array.
<?php
$static=array(
array('point'=>50,'title'=>'TITLE 1','id'=>54632),
array('point'=>50,'title'=>'TITLE 2','id'=>54344),
array('point'=>50,'title'=>'TITLE 3','id'=>34225),
array('point'=>50,'title'=>'TITLE 4','id'=>2323245),
array('point'=>50,'title'=>'TITLE 5','id'=>23872445),
);
$user=array(
array('id'=>2323245,'title'=>'TITLE 1','point'=>50),
array('id'=>54344,'title'=>'TITLE 2','point'=>50),
array('id'=>34225,'title'=>'TITLE 3','point'=>50)
);
$final=array();
foreach ($static as $entry) {
$final[]=array(
'found'=>in_array($entry['id'],array_column($user,'id'))?1:0,
'id'=>$entry['id'],
'title'=>$entry['title'],
'point'=>$entry['point']
);
}
echo"<pre>".print_r($final,true)."</pre>";
With your data, the output is:
Array
(
[0] => Array
(
[found] => 0
[id] => 54632
[title] => TITLE 1
[point] => 50
)
[1] => Array
(
[found] => 1
[id] => 54344
[title] => TITLE 2
[point] => 50
)
[2] => Array
(
[found] => 1
[id] => 34225
[title] => TITLE 3
[point] => 50
)
[3] => Array
(
[found] => 1
[id] => 2323245
[title] => TITLE 4
[point] => 50
)
[4] => Array
(
[found] => 0
[id] => 23872445
[title] => TITLE 5
[point] => 50
)
)
EDIT
Given the more complex structure of your actual arrays, I nested several array_column functions to access the deeper "data > achievement > id" keys in your user array:
$user_achvmts=array_column(array_column(array_column($user,'data'),'achievement'),'id');
See the example below:
// initialize the "static" and "user" arrays
$static=array (
0 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement2',
'title' => 'Achievement 2',
'id' => 644081262362202
),
1 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement3',
'title' => 'Achievement 3',
'id' => 912599152147444
),
2 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement5',
'title' => 'Achievement 5',
'id' => 913757345379232
),
3 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement6',
'title' => 'Achievement 6',
'id' => 921989084564878
),
4 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement1',
'title' => 'Achievement 1',
'id' => 968802826528055
),
5 => array(
'data' => array(
'points' => 50
),
'description' => 'you unlock the achievement4',
'title' => 'Achievement 4',
'id' => 1149671038394021
)
);
$user=array(
0=>array(
'data' => array(
'importance' => 0,
'achievement' => array (
'id' => 644081262362202,
'title' => 'Achievement 2',
'type' => 'game.achievement',
'url' => 'http://www.***.com/achievements/achievement2.html'
)
),
'id' => 104693166566570
),
1 => array (
'data' => array (
'importance' => 0,
'achievement' => array (
'id' => 968802826528055,
'title' => 'Achievement 1',
'type' => 'game.achievement',
'url' => 'http://www.***.com/achievements/achievement1.html'
)
),
'id' => 104023386633548
)
);
// build array of user achievement IDs
$user_achvmts=array_column(array_column(array_column($user,'data'),'achievement'),'id');
// generate final array, with "found" values
$final=array();
foreach ($static as $entry) {
$final[]=array(
'found'=>in_array($entry['id'],$user_achvmts)?1:0,
'id'=>$entry['id'],
'title'=>$entry['title'],
'description'=>$entry['description'],
'points'=>$entry['data']['points']
);
}
echo"<pre>".print_r($final,true)."</pre>";
The result is:
Array
(
[0] => Array
(
[found] => 1
[id] => 644081262362202
[title] => Achievement 2
[description] => you unlock the achievement2
[points] => 50
)
[1] => Array
(
[found] => 0
[id] => 912599152147444
[title] => Achievement 3
[description] => you unlock the achievement3
[points] => 50
)
[2] => Array
(
[found] => 0
[id] => 913757345379232
[title] => Achievement 5
[description] => you unlock the achievement5
[points] => 50
)
[3] => Array
(
[found] => 0
[id] => 921989084564878
[title] => Achievement 6
[description] => you unlock the achievement6
[points] => 50
)
[4] => Array
(
[found] => 1
[id] => 968802826528055
[title] => Achievement 1
[description] => you unlock the achievement1
[points] => 50
)
[5] => Array
(
[found] => 0
[id] => 1149671038394021
[title] => Achievement 4
[description] => you unlock the achievement4
[points] => 50
)
)
Note that array_column is only available in PHP >= 5.5.0. For older versions, see the Recommended userland implementation for PHP lower than 5.5.
As an alternative to array_column, you could use array_map to build an array of the user IDs:
$user_achvmts = array_map( function($v) {return $v['data']['achievement']['id'];}, $user);
Or even just iterate through the user array:
$user_achvmts=[];
foreach ($user as $v) { $user_achvmts[]=$v['data']['achievement']['id']; }

How should I merge the associative array with $_FILES array in a way I wanted?

I've an associative array called $data as follows:
Array
(
[op] => edit
[pt_id] => 4
[form_submitted] => yes
[pt_doc_title] => Array
(
[1] => Test Document
[2] => New Joining
[3] => Hallo Jolly
)
[pt_doc_id] => Array
(
[0] => 6
[1] => 7
)
[submit] => Update
)
In order to keep all the package type documents data together I've manipulated the above array as follows:
foreach ($data['pt_doc_title'] as $key => $title) {
$id = isset($data['pt_doc_id'][$key-1]) ? $data['pt_doc_id'][$key-1] : null;
$data['pt_documents_data'][] = array(
'pt_doc_title' => $title,
'pt_doc_id' => $id
);
}
unset($data['pt_doc_title'], $data['pt_doc_id']);
After manipulation I'm getting following array $data as follows:
Array
(
[op] => edit
[pt_id] => 4
[form_submitted] => yes
[submit] => Update
[pt_documents_data] => Array
(
[0] => Array
(
[pt_doc_title] => Test Document
[pt_doc_id] => 6
)
[1] => Array
(
[pt_doc_title] => New Joining
[pt_doc_id] => 7
)
[2] => Array
(
[pt_doc_title] => Hallo Jolly
[pt_doc_id] =>
)
)
)
My issue is I'm haivng another array called $_FILES as follows and I want to merge one of it's key(name) into above array in a same manner.
Array
(
[document_file_name_1] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
[document_file_name_2] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
[document_file_name_3] => Array
(
[name] => FAQ.doc
[type] => application/msword
[tmp_name] => /tmp/phpFiBYKB
[error] => 0
[size] => 35840
)
)
That is if there exists a value under [name] then the final array should be as follows. As there is a value present only in last array element of array $_FILES
Array
(
[op] => edit
[pt_id] => 4
[form_submitted] => yes
[submit] => Update
[pt_documents_data] => Array
(
[0] => Array
(
[pt_doc_title] => Test Document
[pt_doc_id] => 6
[pt_doc_file_iname] =>
)
[1] => Array
(
[pt_doc_title] => New Joining
[pt_doc_id] => 7
[pt_doc_file_iname] =>
)
[2] => Array
(
[pt_doc_title] => Hallo Jolly
[pt_doc_id] =>
[pt_doc_file_iname] => FAQ.doc
)
)
)
Can anyone please help me in creation of such final array?
Simplest way would be to walk the $_FILES array and extract the id from the last segment of the field name... then use that -1 as the basis for adding the file to your result array.
Something like this should get you there (untested):
foreach($_FILES as $k => $file){
$index_to_update = trim(substr($k, strrpos($k, "_")+1))-1;
$res["pt_document_data"][$index_to_update]["pt_doc_file_iname"] = isset($file["name"])?$file["name"]:"";
}
That is assuming $res is the array that is the parent of the pt_document_data element.

PhP - Search massive array for value, return parent key.

Q: How to Search Massive Multi-Dimensional Array for Single Value, and Return Parent Array?
I have this massive json that represents all of the achievements in WoW.
http://us.battle.net/api/wow/data/character/achievements
I converted it into an array using json_decode. This then leaves me with a very massive array that I need to search all of its levels until I find a specific value, I then need to return the parent array of that value.
ex:
This is one small part of the decoded array.
[0] => Array
(
[id] => 7385
[title] => Pub Crawl
[points] => 10
[description] => Complete the Brewmaster scenario achievements listed below.
[reward] => Reward: Honorary Brewmaster Keg
[rewardItems] => Array
(
[0] => Array
(
[id] => 87528
[name] => Honorary Brewmaster Keg
[icon] => inv_holiday_brewfestbuff_01
[quality] => 3
[itemLevel] => 90
[tooltipParams] => Array
(
)
[stats] => Array
(
)
[armor] => 0
)
)
[icon] => inv_misc_archaeology_vrykuldrinkinghorn
[criteria] => Array
(
[0] => Array
(
[id] => 20680
[description] => Spell No Evil
[orderIndex] => 0
[max] => 1
)
[1] => Array
(
[id] => 20681
[description] => Yaungolian Barbecue
[orderIndex] => 1
[max] => 1
)
[2] => Array
(
[id] => 20682
[description] => Binan Village All-Star
[orderIndex] => 2
[max] => 1
)
[3] => Array
(
[id] => 20683
[description] => The Keg Runner
[orderIndex] => 3
[max] => 1
)
[4] => Array
(
[id] => 20684
[description] => Monkey in the Middle
[orderIndex] => 4
[max] => 1
)
[5] => Array
(
[id] => 20685
[description] => Monkey See, Monkey Kill
[orderIndex] => 5
[max] => 1
)
[6] => Array
(
[id] => 20686
[description] => Don't Shake the Keg
[orderIndex] => 6
[max] => 1
)
[7] => Array
(
[id] => 20687
[description] => Party of Six
[orderIndex] => 7
[max] => 1
)
[8] => Array
(
[id] => 20688
[description] => The Perfect Pour
[orderIndex] => 8
[max] => 1
)
[9] => Array
( re
[id] => 20689
[description] => Save it for Later
[orderIndex] => 9
[max] => 1
)
[10] => Array
(
[id] => 20690
[description] => Perfect Delivery
[orderIndex] => 10
[max] => 1
)
)
[accountWide] =>
[factionId] => 2
)
I am attempting to create a function where I can just simply enter the achievement ID, which in this exmple is 7385, and have the parent array which would be [0] => Array (...); returned, so i can then grab the achievement details from that array.
I am not sure if this is really a proper question, as I am not sure as where to start.
So far I have just started breaking the original massive array down into its 10 equally as massive categories, and then searching them each individually, but I would like to just be able to search the main array once instead of searching each category array individually.
ex:
$allAchieves = file_get_contents('http://us.battle.net/api/wow/data/character/achievements');
$allAchieves = json_decode($allAchieves, true);
$generalAchieves = $allAchieves[achievements][0][achievements];
$quests = $allAchieves[achievements][1][categories];
$explorationAchieves = $allAchieves[achievements][2][categories];
$pvp = $allAchieves[achievements][3][categories];
$dungeonAndRaids = $allAchieves[achievements][4][categories];
$professions = $allAchieves[achievements][5][categories];
$reputation = $allAchieves[achievements][6][categories];
$scenarios = $allAchieves[achievements][7][categories];
$worldEvents = $allAchieves[achievements][8][categories];
$petbattle = $allAchieves[achievements][9][categories];
$featsOfStrength = $allAchieves[achievements][10][categories];
Hopefully someone can help, as the other threads I have seen sofar on array searching seem too simple to be of any help as the arrays they are dealing with are nothing to the size of the one I have here.
Thanks for the suggestions, but I solved the issue using a different approach found here:
http://us.battle.net/wow/en/forum/topic/8892160022?page=1#4

Fetching mysql records from CakePHP with specific index

I am using the following cakephp query to retrieve data from mysql:
$tops = $this->PageBanner->find('all', array(
'conditions' => array(
'PageBanner.status' => 1
),
'fields' => array(
'PageBanner.page_url',
'PageBanner.image',
'PageBanner.logo',
'PageBanner.logo_text',
'PageBanner.content'
)
));
This query returns me the following results:
[0] => Array
(
[PageBanner] => Array
(
[page_url] => index
[image] => home_banner.png
[logo] => home_logo.png
[logo_text] => abc
[content] => abc.
)
)
[1] => Array
(
[PageBanner] => Array
(
[page_url] => write_review
[image] => kids2.png
[logo] => home_logo.png
[logo_text] => abc
[content] => abc.
)
)
But I want the data to be returned in the following format:
[index] => Array
(
[page_url] => index
[image] => home_banner.png
[logo] => home_logo.png
[logo_text] => abc
[content] => abc.
)
[write_review] => Array
(
[page_url] => write_review
[image] => kids2.png
[logo] => home_logo.png
[logo_text] => abc
[content] => abc.
)
I need page_url field content in place of Array index (e.i. 0, 1). Is that possible to get data in this format or I need to manually configure the arrays?
$result = Set::combine($tops, '{n}.PageBanner.page_url', '{n}.PageBanner');
pr($result);

MongoDB - help with a PHP query

I have the following object stored in a MongoDB:
[_id] => MongoId Object (
)
[horses] => Array (
[0] => Array (
[name] => Youve Been Mowed
[selectionId] => 3004097
)
[1] => Array (
[name] => Rascal In The Mix
[selectionId] => 3460932
)
[2] => Array (
[name] => Clumber Place
[selectionId] => 2986884
)
[3] => Array (
[name] => Pretty Orchid
[selectionId] => 2581717
)
[4] => Array (
[name] => Astrodonna
[selectionId] => 2568095
)
[5] => Array (
[name] => Just Sam
[selectionId] => 2511403
)
[6] => Array (
[name] => Many Welcomes
[selectionId] => 2866423
)
[7] => Array (
[name] => Two Turtle Doves
[selectionId] => 3857873
)
[8] => Array (
[name] => Piquante
[selectionId] => 3372813
)
[9] => Array (
[name] => Nimmys Special
[selectionId] => 3066557
)
)
[marketId] => 101531031
[marketName] => 7f Hcap
Now I want to add a new field:
[_id] => MongoId Object (
)
[horses] => Array (
[0] => Array (
[name] => Youve Been Mowed
[selectionId] => 3004097
[odds] => Array(
10000000 => 1.5
10000020 => 1.6
10000030 => 1.7
)
)
...
etc.
...
The 100000XX is a timestamp and the 1.X are the odds
I'm really banging my head off the desk here. Any suggestions much appreciated.
Here's what I have sofar (wrong):
foreach($horses as &$horse)
{
$newdata=array('$set'=>array($horse['odds']=>$price));
$filter=array("marketId"=>$marketId);
$c->update($filter,$newdata);
}
You need to use dot notation:
foreach($horses as &$horse)
{
$newdata=array('$set'=>array('horses.odds'=> array($horses['odds'] => $price)));
$filter=array("marketId"=> $marketId);
$c->update($filter,$newdata);
}
See http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29.
Thanks so much for your reply. Are you the Kristina from the MongoDB Perl module on CPAN? :)
Here's my working code:
$data_object=null;
for($i=0;$i<sizeof($horses);$i++)
{
$data_object->timestamp=$time;
$data_object->niceTime=date("c");
$data_object->price=$price;
$this_horse=$horses[$i];
if($this_horse['selectionId']==$horseId)
{
$newdata=array('$push'=>array("horses.$i.odds"=>$data_object));
$filter=array();
$options=array('upsert'=>true);
$c->update($filter,$newdata,$options);
}
}

Categories