How to classify array items? - php

I have a query which fetches all comments for question and answers in one page (each page is containing at least one post (question), and maybe plus one or more posts (answers)). Now I need to separate comments according to its own question or answers.
The result of my query (fetching all comments) is something like this:
while ($results = $sth->fetch(PDO::FETCH_ASSOC)) {
echo '<pre>';
print_r($results);
}
/* Output:
Array
(
[id] => 1
[post_id] => 1
[content] => Have you any tried so far?
)
Array
(
[id] => 2
[post_id] => 3
[content] => Great answer, upvote
)
Array
(
[id] => 3
[post_id] => 3
[content] => That semicolon is redundant in line 5. Pplease edit it
)
Array
(
[id] => 4
[post_id] => 2
[content] => Won't work ...!
)
Array
(
[id] => 5
[post_id] => 3
[content] => #alex You are right thanks, Edited.
)
So, as you see in the output, all comments are mixed.. Now I need to classify them. Something like this:
/* NewOutput:
[1] => Array
post_id ^ (
[0] => Array
(
[id] => 1
[content] => Have you any tried so far?
)
)
[2] => Array
post_id ^ (
[0] => Array
(
[id] => 4
[content] => Won't work ...!
)
)
[3] => Array
post_id ^ (
[0] => Array
(
[id] => 2
[content] => Great answer, upvote
)
[1] => Array
(
[id] => 3
[content] => That semicolon is redundant in line 5. Pplease edit it
)
[2] => Array
(
[id] => 5
[content] => #alex You are right thanks, Edited.
)
)
Well, Now I want to know, how can I create a nested array according to the value of specific key in the array? exactly like above.

Try this...
$output = array();
foreach($results as $r){
$key = "post_".$r["post_id"];
if(!array_key_exists($key, $output)){
$output[$key] = array();
}
array_push($output[$key], array("id"=>$k["id"], "content"=>$k["content"]));
}
print_r($output);

Related

Getting out the value of a key in multidimentional array in php

In my php query I got this output:
{"projects":[{"id":127,"name":"efrat","status":{"id":10,"name":"development","label":"development"},"description":"","enabled":true,"view_state":{"id":10,"name":"public","label":"public"},"access_level":{"id":90,"name":"administrator","label":"administrator"},"custom_fields":[{"id":1,"name":"Customer email","type":"email","default_value":"","possible_values":"","valid_regexp":"","length_min":0,"length_max":50,"access_level_r":{"id":10,"name":"viewer","label":"viewer"},"access_level_rw":{"id":10,"name":"viewer","label":"viewer"},"display_report":true,"display_update":true,"display_resolved":true,"display_closed":true,"require_report":false,"require_update":false,"require_resolved":false,"require_closed":false}],"versions":[],"categories":[{"id":93,"name":"Monitor","project":{"id":0,"name":null}},{"id":31,"name":"Proactive","project":{"id":0,"name":null}},{"id":30,"name":"Project","project":{"id":0,"name":null}},{"id":29,"name":"Support","project":{"id":0,"name":null}}]}]}
after using 'json_decode' method on it, I get this:
"(
[projects] => Array
(
[0] => Array
(
[id] => 127
[name] => myprojectname
[status] => Array
(
[id] => 10
[name] => development
[label] => development
)
[description] =>
[enabled] => 1
[view_state] => Array
(
[id] => 10
[name] => public
[label] => public
)
[access_level] => Array
(
[id] => 90
[name] => administrator
[label] => administrator
)
[custom_fields] => Array
(
[0] => Array
(
[id] => 1
[name] => Customer email
[type] => email
[default_value] =>
[possible_values] =>
[valid_regexp] =>
[length_min] => 0
[length_max] => 50
[access_level_r] => Array
(
[id] => 10
[name] => viewer
[label] => viewer
)
[access_level_rw] => Array
(
[id] => 10
[name] => viewer
[label] => viewer
)
[display_report] => 1
[display_update] => 1
[display_resolved] => 1
[display_closed] => 1
[require_report] =>
[require_update] =>
[require_resolved] =>
[require_closed] =>
)
)
[versions] => Array
(
)
[categories] => Array
(
[0] => Array
(
[id] => 93
[name] => Monitor
[project] => Array
(
[id] => 0
[name] =>
)
)
[1] => Array
(
[id] => 31
[name] => Proactive
[project] => Array
(
[id] => 0
[name] =>
)
)
[2] => Array
(
[id] => 30
[name] => Project
[project] => Array
(
[id] => 0
[name] =>
)
)
[3] => Array
(
[id] => 29
[name] => Support
[project] => Array
(
[id] => 0
[name] =>
)
)
)
)
)
)"
In my PHP, how can I release the "name" object value (the result should be 'myprojectname') from this array? I've tried many foreach loops that got me nowhere.
Thank you,
It looks like you have one object, that when decoded actually only has one array item. So, in your case, ‘myprojectname’ may simply be “$projects[0][‘name’]”
If many array items, you could
foreach ($projects as $project) {
echo $project[‘name’];
}
EDIT: I took object provided and json_decoded it myself, it doesn't match the json_decoded item presented by OP -- the first image shows the code to var_dump 'name' OP desired, part of the code also below:
$decoded = json_decode($obj);
$projects = $decoded->projects;
$name = $projects[0]->name;
Your 'projects' contains an array ("projects":[{"id":127, ... }]). I assume that the 'projects'-array might contain multiple 'project'-objects like this?
{
"projects":
[
{
"id":127,
"name":"my-project"
},
{
"id":128,
"name":"my-other-project"
}
]
}
In that case you need the arrow notation to access the name property, for example:
foreach ($projects as $project_object) {
foreach ($project_object as $project) {
echo $project->name . '<br/>';
}
}
EDIT:
I took a minimal code example of the OP and got the expected result:
Can you add more details in your code snippets in your original question or provide us with a working example of your code?
There are some online PHP sandboxes that can help you with this. For example: I stripped out all code that does not seem related to your question and got the result you are looking for in two different ways:
http://sandbox.onlinephpfunctions.com/code/009c53671fd9545e4fcecfe4b0328974381ee2ce
It is also a good idea to sum up all the foreach loops that you already tried, so we can see if you were nearly there with your own solution. This way we can understand your question better and it prevents us from offering solutions that you already used.

PHP match values between 2 arrays not same key

I have made researches and havent fount any solutions for this yet. So final thought is come to Stackoverflow and ask the question.
I have 2 array like below:
BigArray
Array
(
[0] => Array
(
[id] => 1
[category_name] => Accountancy
[category_name_vi] => Kế toán
[category_id] => 1
)
[1] => Array
(
[id] => 2
[category_name] => Armed forces
[category_name_vi] => Quân đội
[category_id] => 2
)
[2] => Array
(
[id] => 3
[category_name] => Admin & Secretarial
[category_name_vi] => Thư ký & Hành chính
[category_id] => 3
)
[3] => Array
(
[id] => 4
[category_name] => Banking & Finance
[category_name_vi] => Tài chính & Ngân hàng
[category_id] => 4
)
)
and SmallArray:
Array
(
[0] => Array
(
[id] => 7
[category_id] => 2
[jobseeker_id] => 1
)
[1] => Array
(
[id] => 8
[category_id] => 3
[jobseeker_id] => 1
)
)
Ok, now I wanted to match each category_id from SmallArray link with respectively category_name from BigArrayand the output I only need matched values between SmallArray and BigArraywhere category_id of SmallArray is key and category_name of BigArray is value like below:
Matched array:
Array
(
[0] => Array
(
[2] => Armed forces
)
[1] => Array
(
[3] => Admin & Secretarial
)
)
So far, I have tried array_intersect, 2 foreach loops but no luck. Any advise would be very appreciated :(
Thanks
This should do that:
foreach ($smallArray as $smallKey => $smallElement) {
foreach ($bigArray as $bigKey => $bigElement) {
if ($bigElement['id'] == $smallElement['category_id']) {
$smallArray[$smallKey] = array(
$bigElement['id'] => $bigElement['category_name'],
);
break; // for performance and no extra looping
}
}
}
After these loops, you have what you want in $smallArray.

Yii createCommand() return data set in different array format

I'm a beginner in this framework. Though I have gone over the basics, there is one thing which is troubling me. As of now, I'm using
$group_sql = "SELECT uid FROM {$table}";
$group_users = Yii::app()->db->createCommand($group_sql)->queryAll();
print_r($group_users);
results in
Array
(
[0] => Array
(
[uid] => 2
)
[1] => Array
(
[uid] => 3
)
[2] => Array
(
[uid] => 4
)
[3] => Array
(
[uid] => 5
)
)
But I'd like to change the format in which the data is returned. What I'm looking for is something like
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 5
)
OR
Array
(
[uid] => Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 5
)
)
I'm aware that I can go through the documentation and get my answer, but due to time constraints, I'm taking the liberty to shamelessly ask this over here.
Thanks in advance.
Use queryColumn() method instead of queryAll()

Two Arrays, One Output (How to ForEach?)

Is there a way to foreach() through one array based on a matching value with a different key in another array? In this example, I have a category array ($cat_data) with cat_id as a key and an image array ($img_data) with category_id as a key.
Array (
[0] => Array (
[cat_id] => 1
[cat_name] => Category 1
)
[1] => Array (
[cat_id] => 2
[cat_name] => Category 2
)
)
Array (
[0] => Array (
[img_id] => 2
[img_name] => demo1.jpg
[img_label] => Demo 1
[category_id] => 2
[img_order] => 1
)
[1] => Array (
[img_id] => 3
[img_name] => demo2.jpg
[img_label] => Demo 2
[category_id] => 2
[img_order] => 2
)
[2] => Array (
[img_id] => 4
[img_name] => demo3.jpg
[img_label] => Demo 3
[category_id] => 1
[img_order] => 1
)
)
What I want is to output my display so it looks like the following:
Category 1
demo3.jpg
Category 2
demo1.jpg
demo2.jpg
Since I'm really not great at fully grasping arrays, I thought I'd try Stack, and I haven't been able to find an answer to my question, partially because I'm not sure what to ask for precisely. Any help??
The naïve way:
foreach ($cat_data as $cat) {
echo $cat['cat_name'];
foreach ($img_data as $img) {
if ($img['category_id'] != $cat['cat_id']) {
continue;
}
echo $img['img_name'];
}
}
This is rather inefficient, since it loops through the $imgs array several times, but easy and works.
More efficient:
$images = array();
foreach ($img_data as $img) {
$images[$img['category_id']][] = $img;
}
foreach ($cat_data as $cat) {
echo $cat['cat_name'];
if (isset($images[$cat['cat_id']])) {
foreach ($images[$cat['cat_id']] as $img) {
echo $img['img_name'];
}
}
}
This first groups all images by category into a new array, which you can then loop over directly once.
I would urge you to redesign your array when you fill them with data to instead look something like this.
Array (
[0] => Array (
[cat_id] => 1
[cat_name] => Category 1
[images] = Array(
[0] => Array (
[img_id] => 4
[img_name] => demo3.jpg
[img_label] => Demo 3
[category_id] => 1
[img_order] => 1
)
)
)
[1] => Array (
[cat_id] => 2
[cat_name] => Category 2
[images] = Array(
[0] => Array (
[img_id] => 4
[img_name] => demo3.jpg
[img_label] => Demo 3
[category_id] => 1
[img_order] => 1
)
[1] => Array (
[img_id] => 2
[img_name] => demo1.jpg
[img_label] => Demo 1
[category_id] => 2
[img_order] => 1
)
)
)
)
Then you would have all the relational data connected and would just have to loop through your array of categories and print the images associated with each one in turn. The numbered indexes could even be changed to associative names if the id of the catagory weren't important for example. Then the array could be indexed with the name of the category and just contain the images of that category.
If the images are to be used in other places where you initial layout of those fits better you could still use this layout for your main data graph. Just replace the actual data of the images in the images array under each category with a reference to the actual image object.

Pushing a value onto the end of an array

I have the following array, it's full of gibberish (I got bored using lorem ipsum so I started typing random stuff -- I'm testing ¬_¬).
I used mysqli_fetch_array to fetch this array.
[array1]
Array
(
[0] => Array
(
[title] => this is a new thread, and it is great and it should work
[thread_id] => 27
[content] => <p>hello, how are you? and what are you doing y'all and this should work</p>
[username] => umar
[author_id] => 12
[tags] => Array
(
[0] => lorem
)
)
[1] => Array
(
[title] => this is my second thread and it should work fine, just fine
[thread_id] => 28
[content] => <p>this is is good, that I think it should have a thread of its own, don't you think?</p>
[username] => umarrazzaq
[author_id] => 12
[tags] => Array
(
[0] => thread
[1] => less
)
)
)
I have another array [array2]:
Array ( [0] => Array ( [replies] => 2 [id] => 27 )
[1] => Array ( [replies] => 1 [id] => 28 ) )
I want to push this second array onto the first array, where the IDs match.
e.g.
So the first array will become:
[0] => Array
(
[title] => this is a new thread, and it is great and it should work
[thread_id] => 27
[content] => <p>hello, how are you? and what are you doing y'all and this should work</p>
[username] => umar
[author_id] => 12
[tags] => Array
(
[0] => lorem
)
**[replies] => 2**
)
I've tried passing by reference and using array_push in a foreach loop, but it only does it for one.
try this:
foreach($array1 as $key=>&$arr){
$arr['replies'] = $array2[$key]['replies']
}
It seems that you could do this also with a JOIN on your table
foreach($array1 as $key => $value)
{
$array1[$value['thread_id']] = $value;
}
foreach($array2 as $value)
{
array_push($array1[$value['id']], $value);
}
if i am getting your question correct then you want to merge array where array2.id and array1.thread_id is same. In that case you can't use array_merge. Unless you change your second array as something like below.
array(
[$thead_id] => Array ( [replies] => 2)
....
)
then you can use array_merge easily .

Categories