Hey all, I have a huge array coming back as search results and I want to do the following:
Walk through the array and for each record with the same "spubid" add the following keys/vals: "sfirst, smi, slast" to the parent array member in this case, $a[0]. So the result would be leave $a[0] in tact but add to it, the values from sfirst, smi and slast from the other members in the array (since they all have the same "spubid"). I think adding the key value (1, 2, 3) to the associate key (sfirst1=> "J.", smi1=>"F.", slast1=>"Kennedy") would be fine. I would then like to DROP (unset()) the rest of the members in the array with that "spubid". Here is a simplified example of the array I am getting back and in this example all records have the same "spubid":
Array (
[0] =>
Array (
[spubid] => A00502
[sfirst] => J.
[smi] => A.
[slast] => Doe
[1] =>
Array (
[spubid] => A00502
[sfirst] => J.
[smi] => F.
[slast] => Kennedy
[2] =>
Array (
[spubid] => A00502
[sfirst] => B.
[smi] => F.
[slast] => James
[3] =>
Array (
[spubid] => A00502
[sfirst] => S.
[smi] => M.
[slast] => Williamson
)
)
So in essence I want to KEEP $a[0] but add new keys=>values to it (sfirst$key, smi$key, slast$key) and append the values from "sfirst, smi, slast" from ALL the members with that same "spubid" then unset $a[1]-[3].
Just to clarify my IDEAL end result would be:
Array (
[0] =>
Array (
[spubid] => A00502
[sfirst] => J.
[smi] => A.
[slast] => Doe
[sfirst1] => J.
[smi1] => F.
[slast1] => Kennedy
[sfirst2] => B.
[smi2] => F.
[slast2] => James
[sfirst3] => S.
[smi3] => M.
[slast3] => Williamson
)
)
In most cases I will have a much bigger array to start with that includes a multitude of "spubid"'s but 99% of publications have more than one author so this routine would be very useful in cleaning up the results and making the parsing process for display much easier.
***UPDATE
I think by over simplifying my example I may have made things unclear. I like both Chacha102's and zombat's responses but my "parent array" contains A LOT more than just a pubid, that just happens to be the primary key. I need to retain a lot of other data from that record, a small portion of that is the following:
[spubid] => A00680
[bactive] => t
[bbatch_import] => t
[bincomplete] => t
[scitation_vis] => I,X
[dentered] => 2009-08-03 12:34:14.82103
[sentered_by] => pubs_batchadd.php
[drev] => 2009-08-03 12:34:14.82103
[srev_by] => pubs_batchadd.php
[bpeer_reviewed] => t
[sarticle] => A case study of bora-driven flow and density changes on the Adriatic shelf (January 1987)
.
.
.
.
.
There are roughly 40 columns that come back with each search query. Rather than hard coding them as these examples do with the pubid, how can I include them while still making the changes as you both suggested. Creating a multi-dimensional array (as both of you suggested) with the authors being part of the multi-dimension is perfectly fine, thank you both for the suggestion.
**** UPDATE:
Here is what I settled on for a solution, very simple and gets the job done nicely. I do end up creating a multi-dimensional array so the authors are broken out there.
Over simplified solution:
$apubs_final = array();
$spubid = NULL;
$ipub = 0;
foreach($apubs as $arec)
{
if($spubid != $arec['spubid'])
{
$ipub++;
$apubs_final[$ipub] = $arec;
// insert UNSET statements here for author data
$iauthor = 0;
$spubid = $arec['spubid'];
}
$iauthor++;
$apubs_final[$ipub]['authors'][$iauthor]['sauthor_first'] = $arec['sfirst'];
}
Thanks to everybody who responded, your help is/was much appreciated!
// First, probably the more parsable way.
foreach($array as $key => $values)
{
$end[$spuid] = $values;
$spuid = $values['spuid']
$end[$spuid]['authors'][] = array('sfirst' => $values['sfirst'],
'smi' => $values['smi'],
'slast' => $values['slast']);
}
Which will get an array like this
Array(
[A00502] =>
Array(
[supid] => A00502
.... other values .....
[authors] =>
Array(
[0]=>
Array(
['sfirst'] => '',
['smi'] => '',
['slast'] => '')
)
)
)
I find this way to be much more parse-able if you plan on showing it on a page, because it uses arrays so you can foreach the authors, which is how I've seen many people do it for attributes like that.
If you really do want your ideal format, use this afterwards
$count = 0;
foreach ($end as $supid => $values)
{
$other_end[$count] = $values;
$other_end[$count]['spuid'] = $spuid;
foreach($values['authors'] as $key => $author)
{
if($key == 0)
{
$suffix = '';
}
else
{
$suffix = $key;
}
$other_end[$count]['sfirst'.$suffix] = $author['sfirst'];
$other_end[$count]['smi'.$suffix] = $author['smi'];
$other_end[$count]['slast'.$suffix] = $author['slast'];
}
}
Why not instead make an array keyed on the spubid:
// assuming $array is your array:
$storage = array();
foreach($array as $entry) {
$bid = $entry['spubid'];
if (!isset($storage[$bid])) {
// duplicate entry - taking the author out of it.
$stortmp = $entry;
unset($stortmp['sfirst'], $stortmp['smi'], $stortmp['slast']);
// add an authors array
$stortmp['authors'] = array();
$storage[$bid] = $stortmp;
}
$author = array(
'sfirst' => $entry['sfirst'],
'smi' => $entry['smi'],
'slast' => $entry['slast']);
$storage[$bid]['authors'][] = $author;
}
Now your $storage array should look like:
Array(
"A00502" => Array(
"spubid" => "A00502",
"authors" => Array(
[0] =>
Array (
[sfirst] => J.
[smi] => A.
[slast] => Doe
[1] =>
Array (
[sfirst] => J.
[smi] => F.
[slast] => Kennedy
And you could easily do a foreach on the authors to print them:
foreach ($storage as $pub) {
echo 'Pub ID: '.$pub['spubid']."<br/>";
foreach ($pub['authors'] as $author) {
echo 'Author: '.$author['sfirst'].' '.$author['smi'].' '.$author['slast']."<br/>";
}
}
And as an added bonus, you can access $storage['A00502'].
UPDATED FOR COMMENT
It seems that your array is probably coming from some sort of SQL query that involves a JOIN from a publications table to a authors table. This is making your result dataset duplicate a lot of information it doesn't really need to. There is no reason to have all the publication data transferred/retrieved from the database multiple times. Try rewriting it to get a query of all the books its going to display, then have a "authors" query that does something like:
SELECT * FROM authors WHERE spubid IN ('A00502', 'A00503', 'A00504');
Then convert it into this array to use for your display purposes. Your database traffic levels will thank you.
This code should work exactly as you specified. I took the approach of using a couple of temporary arrays to do correlations between the main array keys and the spubid sub-keys.
/* assume $array is the main array */
$array = array(
array('spubid' => 'A00502','sfirst'=>'J.','smi'=>'A.','slast'=>'Doe'),
array('spubid' => 'A00502','sfirst'=>'J.','smi'=>'F.','slast'=>'Kennedy'),
array('spubid' => 'A00502','sfirst'=>'B.','smi'=>'F.','slast'=>'James'),
array('spubid' => 'BXXXXX','sfirst'=>'B.','smi'=>'F.','slast'=>'James'),
array('spubid' => 'A00502','sfirst'=>'S.','smi'=>'M.','slast'=>'Williamson')
);
//track spubid positions in the main array
$keyPositions = array();
//keys to delete after array iteration
$keyDel = array();
//track how many spubkey increments you've made to the fields
$spubKeys = array();
//fields to copy between spubids
$copyFields = array('sfirst','smi','slast');
foreach($array as $key => $subarr)
{
if (isset($subarr['spubid'])) {
if (isset($keyPositions[$subarr['spubid']])) {
//spubid already exists at a main array key, do the copy
$spubKey = ++$spubKeys[$subarr['spubid']];
foreach($copyFields as $f) {
$array[$keyPositions[$subarr['spubid']]][$f.$spubKey] = $subarr[$f];
}
$keyDel[] = $key;
}
else {
//First time encountering this spubid, mark the position
$keyPositions[$subarr['spubid']] = $key;
$spubKeys[$subarr['spubid']] = 0;
}
}
}
if (count($keyDel)) {
foreach($keyDel as $idx) unset($array[$idx]);
}
var_dump($array);
Related
I will try to explain the data I'm working with first, then I'll explain what I hope to do with the data, then I'll explain what I've tried so far. Hopefully someone can point me in the right direction.
What I'm working with:
I have an array containing survey responses. The first two items are the two answers for the first question and responses contains the number of people who selected those answers. The last three items are the three answers for the other question we asked.
Array
(
[0] => Array
(
[survey_id] => 123456789
[question_text] => Have you made any changes in how you use our product this year?
[d_answer_text] => No
[responses] => 92
)
[1] => Array
(
[survey_id] => 123456789
[question_text] => Have you made any changes in how you use our product this year?
[answer_text] => Yes
[responses] => 30
)
[2] => Array
(
[survey_id] => 123456789
[question_text] => How would you describe your interaction with our staff compared to prior years?
[answer_text] => Less Positive
[responses] => 14
)
[3] => Array
(
[survey_id] => 123456789
[question_text] => How would you describe your interaction with our staff compared to prior years?
[answer_text] => More Positive
[responses] => 35
)
[4] => Array
(
[survey_id] => 123456789
[question_text] => How would you describe your interaction with our staff compared to prior years?
[answer_text] => No Change
[responses] => 72
)
)
What I want to achieve:
I want to create an array where the question_text is used as the key (or I might grab the question_id and use it instead), use the answer_text as a key, with the responses as the value. It would look something like this:
Array
(
[Have you made any changes in how you use our product this year?] => Array
(
[No] => 92
[Yes] => 30
)
[How would you describe your interaction with our staff compared to prior years?] => Array
(
[Less Positive] => 14
[More Positive] => 35
[No Change] => 72
)
)
Here's what I've tried:
$response_array = array();
foreach($result_array as $value){
//$responses_array['Our question'] = array('answer 1'=>responses,'answer 2'=>responses);
$responses_array[$value['question_text']] = array($value['answer_text']=>$value['responses']);
}
This does not work because each loop will overwrite the value for $responses_array[$question]. This makes sense to me and I understand why it won't work.
My next thought was to try using array_merge().
$responses_array = array();
foreach($result as $value){
$question_text = $value['question_text'];
$answer_text = $value['answer_text'];
$responses = $value['responses'];
$responses_array[$question_text] = array_merge(array($responses_array[$question_text],$answer_text=>$responses));
}
I guess my logic was wrong because it looks like the array is nesting too much.
Array
(
[Have you made any changes in how you use our product this year?] => Array
(
[0] => Array
(
[0] =>
[No] => 92
)
[Yes] => 30
)
My problem with array_merge is that I don't have access to all answers for the question in each iteration of the foreach loop.
I want to design this in a way that allows it to scale up if we introduce more questions with different numbers of answers. How can this be solved?
Sounds like a reduce job
$response_array = array_reduce($result_array, function($carry, $item) {
$carry[$item['question_text']][$item['answer_text']] = $item['responses'];
return $carry;
}, []);
Demo ~ https://eval.in/687264
Update
Remove condition (see #Phil comment)
I think you are looking for something like that :
$output = [];
for($i = 0; $i < count($array); $i++) {
$output[$array[$i]['question_text']] [$array[$i]['answer_text']]= $array[$i]['responses'];
}
print_r($output);
Slightly different approach than the answer posted, more in tune with what you'v already tried. Try This:
$responses_array = array();
$sub_array = array();
$index = $result[0]['question_text'];
foreach($result as $value){
$question_text = $value['question_text'];
$answer_text = $value['answer_text'];
$responses = $value['responses'];
if (strcmp($index, $question_text) == 0) {
$sub_array[$answer_text] = $responses;
} else {
$index = $question_text;
$responses_array[$index] = $sub_array;
$sub_array = array();
}
}
Edit: Found my mistake, updated my answer slightly, hopefully this will work.
Edit 2: Working with example here: https://eval.in/687275
I'm having trouble printing the results of this array in loop (to be displayed on the front end). The objective to be able to get the chapter name (eg, Chapter_Name_Unique), that chapter name's total chapter post views count, and then the fullname of each chapter_member within that chapter name (or group). I'm thinking that something isn't structured properly here, because I'm having issues looping through.
Is my logic off?
print_r looks like this:
Array
(
[Chapter_Name_Unique] => Array
(
[chapter_post_views_count] => 3338
[chapter_members] => Array
(
[0] => Array
(
[post_views_count] => 3338
[first_name] => Mary
[last_name] => Jane
[fullname] => maryjane
[chapter_name] => Chapter_Name_Unique
)
)
)
[Chapter_Name_Unique_2] => Array
(
[chapter_post_views_count] => 783
[chapter_members] => Array
(
[0] => Array
(
[post_views_count] => 404
[first_name] => Betty
[last_name] => Lou
[fullname] => bettylou
[chapter_name] => Chapter_Name_Unique_2
)
[1] => Array
(
[post_views_count] => 379
[first_name] => Judy
[last_name] => Jones
[fullname] => judyjones
[chapter_name] => Chapter_Name_Unique_2
)
)
)
)
and the actual functions look like this:
$grouped_types = array();
// to add together post counts of group members
foreach($users as $chapter){
$grouped_types[$chapter['chapter_name']]['chapter_post_views_count'] += $chapter['post_views_count'];
}
// to group on top level by chapter_name
foreach($users as $chapter){
$grouped_types[$chapter['chapter_name']]['chapter_members'][] = $chapter;
}
echo "<pre>";
print_r( $grouped_types );
echo "</pre>";
Try something like (assuming that $users is your array from your print_r())
$grouped_types = array();
foreach($users as $chapter=>$data){
$grouped_types[$chapter]['chapter_post_views_count'] = $data['chapter_post_views_count'];
foreach($data['chapter_members'] as $member){
$grouped_types[$chapter]['chapter_members'][] = $members['fullname'];
}
}
echo "<pre>";
print_r( $grouped_types );
echo "</pre>";
Thanks so much guys, your tips really helped. I wound up using a bit from both, and pulling this together:
foreach( $grouped_types as $chapter_name_unique => $vars) {
$chapter_post_views = $vars['chapter_post_views_count'];
$chapter_members = $vars['chapter_members'];
echo $chapter_name_unique; // echo chapter name (level 1)
echo $chapter_post_views; // echo chapter post views (level 2 - $vars before)
foreach( $vars['chapter_members'] as $member){ // loop through all chapter_members
$vars['chapter_members'][] = $member['fullname'];
echo $member['fullname']; // echo all usernames within the group
}
}
In combination with the two other foreach statements above (they resort and add things together saving to the $grouped_types array), this works exactly as I needed it to. (Hopefully not too much unnecessary looping?)
Thanks again!
I'm using an API which returns some JSON that I output in PHP.
PHP
$result = $api->sendRequest("getUsers", $inputParameters);
$output = json_decode($result, true);
An example of an array returned by the API. I can print out specific field values fine, but I can't figure out how to write a simple if statement that indicates whether or not there are duplicate names within the query result, specifically duplicate [fullName] fields as seen below.
Array
(
[status] => Array
(
[request] => getUsers
[recordsTotal] => 3
[recordsInResponse] => 3
)
[records] => Array
(
[0] => Array
(
[fullName] => Smith, Tom
[firstName] => Tom
[lastName] => Smith
)
[1] => Array
(
[fullName] => Jones, Bill
[firstName] => Bill
[lastName] => Jones
)
[2] => Array
(
[fullName] => Smith, Tom
[firstName] => Tom
[lastName] => Smith
)
)
)
Any help would be greatly appreciated.
Not tested, but maybe try something like
function dupeCheck($array, $attribute = 'fullName') {
$list = array();
foreach($array['records'] as $value) {
if(in_array($value[$attribute], $list))
return true;
$list[] = $value[$attribute];
}
return false;
}
Just iterating over the records, we maintain a list of values of whatever attribute, once it finds one that was already in the array, returns true.
Then just:
if(!dupeCheck($output, 'fullName')) { // no dupes in the API response }
This should work:
$data['records'] = array_map("unserialize", array_unique(array_map("serialize", $data['records'])));
Taken from here and slightly modified.
Simply create an array whose keys will be the fullnames of the entris you've seen so far:
$names = array();
foreach ($output['records'] as $entry){
If (isset($names[$entry['fullname']]){
// do some error processing
echo "'${entry['fullname']}' is a duplicate";
}
$names[$entry['fullname']] = $entry;
}
You should have all the unique entries in $names.
PHP has a lot of built in array functions to help with operations like this. You could try the following:
$names = array_column($output['records'], "fullName");
if(count(array_unique($names)) < count($names)) {
... /* handle duplicate values here */
}
In addition, $names contains a unique array of all the fullName columns from the original array for easy access and traversing. You can use this inside the above if statement to determine which names are duplicates like so:
$names_count = array_count_values($names);
foreach($names_count as $key => $value) {
if(value > 1) {
$dupes[] = $key;
}
}
References:
PHP Array Functions
array_column()
array_unique()
array_count_values()
I am trying to build a new array from simpleXmlElement. I am getting the information I want, just not in the right hierarchy.
$xmlNew1 = new SimpleXMLElement($responseNew1);
$test = array();
foreach ($xmlNew1->children() as $newChild){
$classIden[] = (string)$xmlNew1->class['id'];
$item[] = (string)$xmlNew1->code;
$family[] = (string)$xmlNew1->family;
for($i=0, $count = count($classIden); $i < $count; $i++) {
$test[$item[$i]][$family[$i]]= $classIden[$i];
}
}
print_r($test);
this gives me:
Array
(
[9522] => Array
(
[Mens Hats] => 44
)
[9522-NC-NO SIZE] => Array
(
[Mens Hats] => 44
)
[B287CSQU] => Array
(
[Boys] => 1
)
but I want
Array
(
[9522] => Array
(
[family] => Mens Hats
[classId] => 44
)
Any suggestion? Thanks!
This should probably do it (to replace the main loop contents):
$id = (string)$newChild->class['id'];
$code = (string)$newChild->code;
$family = (string)$newChild->family;
$items[$code] = array(
'family' => $family,
'classId' => $id,
);
Edit
Forgot to use $newChild instead of $xmlNew1.
I don't know your hierarchy because I do not know much about the HTML. You've hidden the structure. However, you should probably build the array in the format you look for directly.
Let us try to make that less complicated. Let's say you have a variable that would contain all the children. So you can pull apart the iteration and loading these children. Loading:
$xmlNew1 = new SimpleXMLElement($responseNew1);
$newChildren = $xmlNew1->children();
I can not say you if $xmlNew1->children() is sufficient to get you all the xml elements you are looking for, but let's just assume so.
Next part is about the iteration. As written you should build the $test array while you iterate over the children - as you partly already did:
$test = array();
foreach ($newChildren as $newChild) {
...
}
Missing part now is to create your structure in $test:
Array(
[9522] => Array(
[family] => Mens Hats
[classId] => 44
)
I like the suggestion #Jack gives here to first assign the values you want to extract to variables of their own and then create the entry.
$newItem = array(
'family' => $family,
'classId' => $id,
);
$test[$code] = $newItem;
Naturally you have to place that into the iteration. When the iteration is done, the $test array should have the format you're looking for.
I hope this is helpful.
Total PHP Noob and I couldn't find an answer to this specific problem. Hope someone can help!
$myvar is an array that looks like this:
Array (
[aid] => Array (
[0] => 2
[1] => 1
)
[oid] => Array(
[0] => 2
[1] => 1
)
)
And I need to set a new variable (called $attributes) to something that looks like this:
$attributes = array(
$myvar['aid'][0] => $myvar['oid'][0],
$myvar['aid'][1] => $myvar['oid'][1],
etc...
);
And, of course, $myvar may contain many more items...
How do I iterate through $myvar and build the $attributes variable?
use array_combine()
This will give expected result.
http://php.net/manual/en/function.array-combine.php
Usage:
$attributes = array_combine($myArray['aid'], $myArray['oid']);
Will yield the results as requested.
Somthing like this if I understood the question correct
$attributes = array();
foreach ($myvar['aid'] as $k => $v) {
$attributes[$v] = $myvar['oid'][$k];
}
Your requirements are not clear. what you mean by "And, of course, $myvar may contain many more items..." there is two possibilties
1st. more then two array in main array. like 'aid', 'oid' and 'xid', 'yid'
2nd. or two main array with many items in sub arrays like "[0] => 2 [1] => 1 [2] => 3"
I think your are talking about 2nd option if so then use following code
$aAid = $myvar['aid'];
$aOid = $myvar['oid'];
foreach ($aAid as $key => $value) {
$attributes['aid'][$key] = $value;
$attributes['oid'][$key] = $myvar['oid'][$key];
}
You can itterate though an array with foreach and get the key and values you want like so
$attributes = array()
foreach($myvar as $key => $val) {
$attributes[$key][0] = $val;
}