I have an associative array as
[name]->user1,
[class_code]->bsc,
[name]->user2,
[class_code]->msc,
[name]->user1,
[class_code]->mca
Now, i want result as
[name]->user1,
[class_code]->bsc,
mca
[name]->user2,
[class_code]->msc
Means if name is same then append the class_code to first one. How should I do that?
My array is
[1] =stdClass Object
([class_code] =Maths
[userid] =365
[avatar] =default.jpg
[username] =user2
)
[2] =stdClass Object
(
[class_code] =Maths
[userid] = 364
[avatar] =default.jpg
[username] =user1
)
[3] =stdClass Object
(
[class_code] =MCA
[userid] =364
[avatar] =default.jpg
[username] =user1
)
[4] =stdClass Object
(
[class_code] =MCA
[userid] =365
[avatar] =default.jpg
[username] =user2
)
Now, while displaying result i want to display records of for ex. user2 as
username:user2
avatar
classcode :MCA,Maths
and not
username:user2
avatar
classcode :MCA
username:user2
avatar
classcode :Maths
how can I do that?
You can't have two values with the same key. Otherwise php wouldn't know what to give you if you asked for $myarray['name'].
You could use nested arrays instead.
eg
[0]->
[name]->user1,
[class_code]->bsc,mca,
[1]->
[name]->user2,
[class_code]->msc
or you could do something like this
[user1]->bsc, mca
[user2]->msc
if you want to have both values in there, you should consider using an array in there
array(
"name"=>"user1,
"class_code"=>"array('mca','bsc'),
"name"=>"user2,
"class_code"=>"msc"
);
if [class_code] must contain a string, you can try
$array[$key] .= $value;
You can make the whole array multidimensional:
$users = array(
0 = array(
"name"=>"user1",
"class_code"=>"bsc"
),
1 = array(
"name"=>"user2",
"class_code"=>"msc"
)
);
Retrieving a value:
$users[1][name] // Returns 'user2'
$users[0][class_code] // Returns 'bsc'
Cycling through values:
foreach($users as $user => $attributes) {
echo "$user: $attributes[name] ($attributes[class_code])<br />";
}
/*
Prints:
0: user1 (bsc)
1: user2 (msc)
*/
Related
I'm having trouble with putting this question to words so ill just use a simple example, hope the title sortof got my problem across.
I'm creating a blog site where I can create blogposts and people can post comments. This is all saved in JSON except for login details which are saved in MySQL.
Now saving the blogposts go fine but I'm now trying to save comments.
Lets say the blogpost array looks like this:
Array
(
[0] => Array
(
[id] => 0
[title] => first blogpost
[content] => blogpost text
)
[1] => Array
(
[id] => 1
[title] => second blogpost
[content] => blogpost 2 text
)
)
Now someone writes a comment on 'second blogpost', I save it into an array like this(user taken from MySQL):
Array
(
[user] => myusername
[comment] => first post was better!
)
Now I want to merge them like this:
Array
(
[0] => Array
(
[id] => 0
[title] => first blogpost
[content] => blogpost text
)
[1] => Array
(
[id] => 1
[title] => second blogpost
[content] => blogpost 2 text
[comments] => Array
(
[user] => myusername
[comment] => first post was better!
)
)
)
I tried searching for a while and I'd expect this to be somewhere on the site already but I can't find it. I tried a couple variations of array_push and array_merge but it always ended up replacing the relevant blogpost instead of adding onto it.
EDIT: Someone noted the new array can't just float around, I think it's better now.
If you had any related key between posts and comments ( like having post_id in comment array ) that would make more sense to merge/put them.
I assume that's your blogpost
Array
(
[0] => Array
(
[id] => 0
[title] => first blogpost
[content] => blogpost text
)
[1] => Array
(
[id] => 1
[title] => second blogpost
[content] => blogpost 2 text
)
)
And your comments should be like:
Array
(
[user] => myusername
[comment] => first post was better!
[post_id] => 1
)
That way, you would be able to find the matched blogpost.
But, outside of your data structure, here is an example to merge an item into an element of an array of array.
A nested loop example.
foreach($posts as &$post){
foreach($comments as $comment){
if($post['id'] == $comment['post_id']){
$post['comments'][] = $comment;
}
}
}
the key here is sending each reference of the element into loop by &$post and then just manipulate them in loop.
Working with indexed arrays. (Like you already have index names as post_id and a comments index as an empty array)
foreach($comments as $comment){
$posts[$comment['post_id']]['comments'][] = $comment;
}
When the blogpost is updated, I assume you can get the id of that blogpost.
Then you can check if your data structure already has a key "comments". If it does not, add the key and create an array containing the comment and the user as the first array.
If it already exists, add a new array with the user and the comment so that there can be multiple comments for each blogpost.
For example using array_map:
$blogPosts = array_map(function ($blogPost) use ($blogPostId, $comment) {
if ($blogPost["id"] === $blogPostId) {
isset($blogPost["comments"]) ? $blogPost["comments"][] = $comment : $blogPost["comments"] = [$comment];
return $blogPost;
}
return $blogPost;
}, $blogPosts);
Php demo
So I fixed it after a bit of thinking
This is the final structure:
Array
(
[0] => Array
(
[id] => 0
[title] => 1st post
[content] => 1st post works!
[date] => 21-01-2019
[comments] => Array
(
[0] => Array
(
[user] => Me
[comment] => hey 1
[date] => 12:02 21-01-2019
)
[1] => Array
(
[user] => Me
[comment] => hey 2
[date] => 12:03 21-01-2019
)
)
)
)
I added a timestamp because of a suggestion here. It's also a simplified version of what I actually use, I tried adding many more comments and on multiple posts which both work.
This is the code, I should mention the ID is in the URL and it's saved as JSON:
$filename = file.json;
$currentArray = json_decode(file_get_contents($filename), true);
$comment = $_POST['comment'];
$username = $_SESSION['username'];
$date = date("H:i d-m-Y");
$id = $_GET['id'];
Pretty straightforward so far, here is how the array is created:
$currentArray[$id]["comments"][] = array (
'user' => $username,
'comment' => $comment,
'date' => $date
);
[$id] saves it to the correct post, ["comments"] saves it to the comments key(or creates it) and the last [] gives every comment a different index inside the ["comments"].
$newJSON = json_encode($currentArray, JSON_PRETTY_PRINT);
file_put_contents($filename, $newJSON);
And lastly encoding it and saving it to JSON.
Hope this helps someone.
I have an array stored in variable $user_top_cat. I loop through all the users on my site and this variable stores their top categories.
On a random user, print_r() gives us:
Array (
[0] => stdClass Object ( [category] => 16 [count] => 8 )
[1] => stdClass Object ( [category] => 17 [count] => 2 )
[2] => stdClass Object ( [category] => 24 [count] => 2 )
)
Now, I want to store the category 17's count value in variable $category_17_count as a string. How do I do this?
Note that the $user_top_cat differs depending on which user I target...
I don't know why you'd want to but yes you could use the category to concatenate it and turn it into a variable then assign the value:
foreach($user_top_cat as $values) {
$cat_num = $values->category;
${"category_".$cat_num."_count"} = $values->count;
}
Sample Output
Will you could use variable varaibles, but how would you know which variables exist?
foreach ($user_top_cat as $cat){
${'category_'.$cat->category.'_count'} = $cat->count;
}
You'd probably be better using an array
foreach ($user_top_cat as $cat){
$categories[$cat->catergory]=$cat->count;
}
Something like:
foreach( $user_top_cat as $myObj ) {
if( $myObj['category'] == 17 ) {
$category_17_count = (string)$myObj['count'];
}
}
Below is a array generated by a query builder.
$random_array = Array ( [0] => Array ( [text] => A great time was had by all! )
[1] => Array ( [text] => KILL SHOT )
[2] => Array ( [text] => How is it possible)
[3] => Array ( [text] => http://www.youtube.com/watch?v=KwGOZpbxU9g )
[4] => Array ( [text] => http://www.youtube.com/watch?v=KwGOZpbxU9g )
)
Currently i am doing like this to print the random value
print_r(array_rand($random_array,1));
This is printing the array key as 3 or 1 etc(random from above array).I want to print the value of the key and not the key.
e.g I want to print the random value like this "http://www.youtube.com/watch?v=KwGOZpbxU9g" or "A great time was had by all!" instead of 3 or 1 which is printing now.
Is it possible to do this.
You will have one more line of code as shown below:
$array_key = array_rand($random_array,1); //get the key
print_r( $random_array[$array_key] ); //use the key to print value
What about simply calling
$randNumber = rand(0,count($random_array))-1; //index in array starts with 0
print (string) $random_array[$randNumber];
I have a result of an SQL query that looks like this
Array
(
[0] => stdClass Object
(
[field_number] => 1
[value] => Joe
)
[1] => stdClass Object
(
[field_number] => 2
[value] => Bloggs
)
[2] => stdClass Object
(
[field_number] => 3
[value] => 12566
)
[3] => stdClass Object
(
[field_number] => 4
[value] => 2000-07-24
)
)
It wont always return all the fields as some are not required therefore not saved to the database.
I know that first name is stored with field number 1. How can I look this up in the object.
EG
$first_name = $result => field_number == 1
I know thats not right, but Im sure there must be a simple way to get this info?
Thanks
If the values in the array are not in order (eg array[0] does not always contain field_number 1) then you will need to iterate the array:
foreach($array as $item){
if($item->field_number==1){
$first_name = $item->value;
break;
}
}
However, if this is the result of an SQL query, probably you need to rewrite the query to give you data in a more useable form
How do I go about reformatting an object?
Array
(
[0] => Array
(
[user_id] => 5
[first_name] => Ace
[last_name] => Black
)
[1] => Array
(
[user_id] => 6
[first_name] => Gary
[last_name] => Surname
)
[2] => Array
(
[user_id] => 7
[first_name] => Alan
[last_name] => Person
)
)
I need to reformat this so the user_id name is changed to just 'id' and the first_name and last_name values are merged into a single value called 'name' so the final result would look like:
Array
(
[0] => Array
(
[id] => 5
[name] => Ace Black
)
)
You might find array_map useful for this
function fixelement($e)
{
//build new element from old
$n=array();
$n['id']=$e['user_id'];
$n['name']=$e['first_name'].' '.$e['last_name'];
//return value will be placed into array
return $n;
}
$reformatted = array_map("fixelement", $original);
As you can see, one downside is that this approach constructs a second copy of the array, but having written the callback, you can always use it 'in place' like this:
foreach($original as $key=>$value)
{
$original[$key]=fixelement($value);
}
If you want to do it in place:
Foreach that array, set the keys to the values you want, unset the keys for the values you no longer want.
If you want a copy of it:
Foreach that array and ETL (extract, transform, load) into another similar array.
If you need further details to help let me know.