Get data from inside array in Php - php

With using of query i am getting result in array, i want to get this data in one array,
I am getting result like following way
Array
(
[0] => stdClass Object
(
[id] => 2
[full_name] => amit sharma
)
[1] => stdClass Object
(
[id] => 1
[full_name] => amit
)
)
I tried with following code but not working for me,Where i am wrong,Here is my code
$sql = "//select query";
$result= $this->db->query($sql)->result();
$total=count($result);
if($total>0)
{
$data=array();
foreach($result as $records)
{
$data[]=$records;
}
echo "<pre>";print_R($data);
}

You can easily loop it and get the values in array as below.
$post_id = array((object) (array(
'id' => 1,
'full_name' => "Amit Sharma",
)), (object) (array(
'id' => 2,
'full_name' => "Amit",
)), (object) (array(
'id' => 3,
'full_name' => "Amit Rohan",
)));
foreach ($post_id as $key => $value)
{ $result[] = array("id"=>$value->id, "full_name"=>$value->full_name); }
echo "<pre>";print_r($result);

Simply use json_encode() and json_decode()
I have created same object as of your example, just ignore the code upto:
$result = [$objOne, $objTwo];
Use your $result
Json encode and decode it to get an associative array in return.
Code:
<?php
$objOne = new stdClass();
$objOne->id = 2;
$objOne->full_name = 'amit sharma';
$objTwo = new stdClass();
$objTwo->id = 1;
$objTwo->full_name = 'amit';
$result = [$objOne, $objTwo];
$arr = json_decode(json_encode($result), TRUE);
echo '<pre>';
print_r($result);
echo '</pre>';
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
Output:
Array
(
[0] => stdClass Object
(
[id] => 2
[full_name] => amit sharma
)
[1] => stdClass Object
(
[id] => 1
[full_name] => amit
)
)
Array
(
[0] => Array
(
[id] => 2
[full_name] => amit sharma
)
[1] => Array
(
[id] => 1
[full_name] => amit
)
)

Related

Getting only the last array data when i looped all arrays

I'm trying to use Facebook Graph API to get comments from the last 2 posts from my accounts
I wrote the code and it works but it only returns the second post (the last array) only
this my code :
$postItems = $postsArray['posts']['data'];
foreach ($postItems as $post) {
$fullPostId = $post['id'];
$comments_number = 10;
$facebook_graph_api2 = "https://graph.facebook.com/v2.4/$fullPostId/comments?access_token=$accToken&pretty=1&summary=true&limit=$comments_number&after";
$jsonData = grab_page($facebook_graph_api2,$accCookie);
$postDataArrays = json_decode($jsonData, true);
$CommentsItems = $postDataArrays['data'];
}
//foreach($CommentItems as $item) {
// echo $users = $item['from']['id'].'\n';
//}
// #$postItems = $postsArray['data'];
/** Update Balance Code **/
$toolId = '87637';
#$itemsCount = #count($CommentItems);
$toolPrice = toolPrice($toolId)*$itemsCount;
$finalBalance = updateBalance($toolPrice);
/** Update Balance Code **/
if ($finalBalance) {
if (isset($CommentItems)) {
echo '{"status":1,"balance":'.$finalBalance.',"message":"Success !","data":"';
foreach($CommentItems as $item) {
echo $users = $item['from']['id'].'\n';
// echo json_encode($users, JSON_FORCE_OBJECT);
// $items[] = $item['from']['id'];
}
// print_r($items);
// echo '{"status":1,"message":"Success !","data":"'.$items.'"}';
echo '"}';
}elseif( isset($postDataArray['error']) && $postDataArray['error']['code']== 1 ){
$msgError = $postDataArray['error']['message'];
echo '{"status":0,"message":"Error !","reason":"'.$msgError.'"}';
}else{
echo '{"status":0,"message":"Error !","reason":"Please Update Your Facebook Access Token"}';
}
}else{
echo '{"status":0,"message":"Error !","reason":"You do not have enough funds on balance"}';
}
The code above returns only last array data not all posts data.
this is an example of $postDataArrays data should be
Array
(
[data] => Array (
[0] => Array
(
[created_time] => 2023-02-08T14:46:12+0000
[from] => Array
(
[name] => Name1
[id] => id1
)
[message] => test Message
[id] => 61xxxxxxxxxxx_12xxxxxxxxxxxx
)
[1] => Array
(
[created_time] => 2023-02-08T14:42:52+0000
[from] => Array
(
[name] => name2
[id] => id2
)
[message] => test Message
[id] => 61xxxxxxxxxx_7xxxxxxxxxxxx
)
)
[paging] => Array
(
[next] => https://graph.facebook.com/v2.4/92xxxxxxxxxxxx_61xxxxxxxxxxxxxxxxxx/comments?access_token=EAAG&pretty=1&summary=true&limit=2&after
)
[summary] => Array
(
[order] => ranked
[total_count] => 58
[can_comment] => 1
)
)
Array
(
[data] => Array
(
[0] => Array
(
[created_time] => 2023-02-07T18:23:40+0000
[from] => Array
(
[name] => name1 from array 2
[id] => id2 from array 2
)
[message] => test Message
[id] => 6xxxxxxxxxxxxxx_xxxxxxxxxxxxxxxx
)
[1] => Array
(
[created_time] => 2023-02-07T18:20:49+0000
[from] => Array
(
[name] => name2 from array 2
[id] => id2 from array 2
)
[message] => test Message
[id] => 6xxxxxxxxxxxxxx_xxxxxxxxxx
)
)
[paging] => Array
(
[next] => https://graph.facebook.com/v2.4/9xxxxxxxxxxxxxxxxxxxxx/comments?access_token=EAAG&pretty=1&summary=true&limit=2&after
)
[summary] => Array
(
[order] => ranked
[total_count] => 121
[can_comment] => 1
)
)
the arrays above should return 4 users but it returns only last 2 users
First i create an array
$responses= array();
And modified the code and put all neded data inside the array
foreach ($postItems as $post) {
$fullPostId = $post['id'];
$comments_number = 3000;
$facebook_graph_api2 = "https://graph.facebook.com/v2.4/$fullPostId/comments?access_token=$accToken&pretty=1&summary=true&limit=$comments_number&after";
$jsonData = grab_page($facebook_graph_api2,$accCookie);
$postDataArray = json_decode($jsonData, true);
$CommentsItems = $postDataArray['data'];
foreach($CommentsItems as $item) {
$users = $item['from']['id'];
$userId['user_id'] = $users;
$responses[] = $userId['user_id'];
}
}
Then , Encoded the the final response to be json , and i decoded it again
$enResponse = json_encode($responses);
$allComments = json_decode($enResponse,true);
To show all data , just loop $allComments
foreach($allComments as $item) {
echo $users = $item.'\n';
}

Create a another associative array inside existing array

I am trying to create an array inside an array so that I can encode it into JSON. I want my array to be like the following:
<pre>Array
(
[user] => John Smith
Array
(
[profile] =>
[podcast] => Array
(
[0] => stdClass Object
(
[id] => 4
[title] => How to display array inside array?
[description] => Unexpected array being displayed!
[category] => 1
[duration] => 0:05:05
[audio] => http://demo.web/uploads/podAudio/PodAudio-20190114102432822.mp3
[image] => http://demo.web/uploads/podImage/PodImage-20190114102432145.jpg
[added_by] => 1
[updated_date] =>
)
)
)
)
</pre>
Following is my code for getting arrays:
<?php
$userList = $user->getAllUserName();
foreach ($userList as $users) {
$fullname = $users->full_name;
$profile = $users->image;
$id = $users->id;
$podcastList = $podcast->getUserPodcast($id);
if (!empty($podcastList)) {
$output = array(
'name' => $fullname,
'profile' => $profile,
'podcast' => $podcastList
);
}
}
$json = array(
'user' => $output
);
echo "<pre>";
print_r($json);
echo "</pre>";
?>
However, the above code is giving me an array which looks like this:
<pre>Array
(
[user] => Array
(
[name] => Lenna Smith
[profile] =>
[podcast] => Array
(
[0] => stdClass Object
(
[id] => 4
[title] => How to display array inside array?
[description] => Unexpected array being displayed!
[category] => 1
[duration] => 0:05:05
[audio] => http://demo.web/uploads/podAudio/PodAudio-20190114102432822.mp3
[image] => http://demo.web/uploads/podImage/PodImage-20190114102432145.jpg
[added_by] => 1
[updated_date] =>
)
)
)
)
</pre>
Is there any code to be replaced or added so that I can the get desired array? Any suggestion will be appreciated.
Simply making the following changes helped me.
<?php
$userList = $user->getAllUserName();
foreach ($userList as $users) {
$fullname = $users->full_name;
$profile = $users->image;
$id = $users->id;
$podcastList = $podcast->getUserPodcast($id);
if (!empty($podcastList)) {
$output[$fullname] = array(
'profile' => $profile,
'podcast' => $podcastList
);
}
}
$json = array(
'user' => $output
);
echo "<pre>";
print_r($json);
echo "</pre>";
?>

How to combine same name with its value in array

hi I have array like this
Array
(
[0] => stdClass Object
(
[name] => text_input
[value] => kalpit
)
[1] => stdClass Object
(
[name] => wpc_chkbox[]
[value] => Option two
)
[2] => stdClass Object
(
[name] => wpc_chkboxasdf[]
[value] => Option one
)
[3] => stdClass Object
(
[name] => wpc_chkboxasdf[]
[value] => Option two
)
[4] => stdClass Object
(
[name] => wpc_inline_chkbox[]
[value] => 1
)
[5] => stdClass Object
(
[name] => wpc_inline_chkbox[]
[value] => 2
)
[6] => stdClass Object
(
[name] => wpc_inline_chkbox[]
[value] => 3
)
[7] => stdClass Object
(
[name] => wpc_radios
[value] => Option one
)
)
now my question is how to combine same name value in onc place, here in above array I have wpc_inline_checkbox[] is repeating 3 times so I want to make it .. I can use array_uniqe() but I want value of other duplicate index...
[4] => stdClass Object
(
[name] => wpc_inline_chkbox[]
[value] => 1,2,3
)
can anyone help me to solve this
Thanks in advance
This is assuming both name/value are strings
<?php
$objects; // This is your array
$sorted = array(); // This is the sorted array
// Loop over your array
foreach($objects as $object)
{
// Check if object exists in sorted array
if( array_key_exists($object->name, $sorted) )
{
// Object with this name is already in sorted array simply add to it
$obj = $sorted[$object->name];
// Update the values
$obj->value = $obj->value . ',' . $object->value;
} else {
// Object is not in the sorted array add it now
$sorted[$object->name] = $object;
}
}
?>
Sorry, your case is not ordinary, so you will need to do it by hand
$properArray = array();
foreach ($originArray as $value) {
if ( ! isset($properArray[$value['name']])) {
$properArray[$value['name']] = array(
'name' = $value['name'],
'value' = ''
);
}
if (isset($properArray[$value['name']]['value'])) {
$properArray[$value['name']]['value'] = $properArray[$value['name']]['value'] . ',' .$value['value']; //better to use array in this place
} else {
$properArray[$value['name']]['value'] = $value['value']
}
}
$originArray = array_values($properArray);
regards,
You have an array of object. You will have to loop through and assign them. Something like
$newArray = [];
foreach ($array as $obj) {
if (!isset($newArray[$obj->name])) {
$newArray[$obj->name] = $obj;
} else {
$newArray[$obj->name]->value .= ",{$obj->value}";
}
}
The new array should look like
["wpc_inline_chkbox[]"] => stdClass Object
(
[name] => wpc_inline_chkbox[]
[value] => "1,2,3"
)
But you should change [value] from string to array.
## Use this ##
$arr = array(
array(
'name' => 'hi'
,'value' => 1
)
,array(
'name' => 'hi'
,'value' => 2
)
, array(
'name' => 'hi2'
,'value' => 1
)
, array(
'name' => 'hi4'
,'value' => 1
)
,array(
'name' => 'hi0'
,'value' => 4
)
, array(
'name' => 'hi0'
,'value' => 3
)
, array(
'name' => 'hi1'
,'value' => 10
)
);
print_r($arr);
$arrTracker = array();
for ($i=0; $i <sizeof($arr) ;$i++) {
for($j = $i+1; $j<sizeof($arr);$j++){
if($arr[$i]['name'] == $arr[$j]['name']){
$arr[$i]['value'] .= ','.$arr[$j]['value'];
$arrTracker[$j] = $j;
}
}
}
// if you want to unset duplicate name and corresponding value, use below forloop, otherwise it's unnecessary
foreach($arrTracker as $tracker){
unset($arr[$tracker]);
}
$arr = array_values($arr);
print_r($arr);

Move value to next element of array

See the attached example that i use to build my array
foreach($something AS $key => $row)
{
$output[] = array("name"=>$row["name"], "points"=>$row["points"]);
}
print_r($output);
Here's the output:
Array
(
[0] => Array
(
[name] => Mark
[points] => 1
)
[1] => Array
(
[name] => Sara
[points] => 2
)
[2] => Array
(
[name] => Jack
[points] => 3
)
)
What i'm trying to do is moving $row["points"] to next array element to get this output:
Array
(
[0] => Array
(
[name] => Mark
[points] =>
)
[1] => Array
(
[name] => Sara
[points] => 1
)
[2] => Array
(
[name] => Jack
[points] => 2
)
)
I don't care if there's some data loss or if my [points] => 3 goes in a new array. I just have to programmatically move $row["points"] always to next element. I'm playing with next() function with no success and also with $key+1 which i'm sure i can't use to achieve the result.
Is it possible to make it on top while i'm building the array or am i forced to move the element later with a separate function? In other words what would you do?
Try This:
$output = array();
$something = array(
'0' => array(
'name' => 'Mark',
'points' => 1,
),
'1' => array(
'name' => 'Sara',
'points' => 2,
),
'2' => array(
'name' => 'Jack',
'points' => 3,
)
);
$point = '';
foreach($something AS $key => $row)
{
$output[$key] = array("name"=>$row["name"], "points"=>$point);
$point = $row['points'];
}
echo '<pre>';
print_r($output);
Try if it helps:
foreach($something AS $key => $row)
{
$output[$key]['name'] = $row["name"];
$output[$key+1]['points'] = $row["points"];
}
print_r($output);
Use:
foreach($array as $key => $each)
{
$array[0]['points'] = "";
$array[$key]['name'] = $each["name"];
if(isset($array[$key+1])) $array[$key+1]['points'] = $each["points"];
}
print_r($array);

Merge two object arrays and remove duplicated objects then sort by column value

I have the following two arrays of objects:
First Array: $array1
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => Muhammad
)
[1] => stdClass Object
(
[id] => 102
[name] => Ibrahim
)
[2] => stdClass Object
(
[id] => 101
[name] => Sumayyah
)
)
Second Array: $array2
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => Muhammad
)
[1] => stdClass Object
(
[id] => 103
[name] => Yusuf
)
)
I want to merge these two object arrays (removing all duplicates) and sorted according to id.
Desired output:
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => Muhammad
)
[1] => stdClass Object
(
[id] => 101
[name] => Sumayyah
)
[2] => stdClass Object
(
[id] => 102
[name] => Ibrahim
)
[3] => stdClass Object
(
[id] => 103
[name] => Yusuf
)
)
These 3 simple steps did the work:
//both arrays will be merged including duplicates
$result = array_merge( $array1, $array2 );
//duplicate objects will be removed
$result = array_map("unserialize", array_unique(array_map("serialize", $result)));
//array is sorted on the bases of id
sort( $result );
Note: Answer by #Kamran helped me come to this simple solution
UPDATE
I am posting the entire code listing here now instead of the previously posted main code, printing both input and output. You can simply copy and paste this code to test.
<?php
function array_to_object($arr) {
$arrObject = array();
foreach ($arr as $array) {
$object = new stdClass();
foreach ($array as $key => $value) {
$object->$key = $value;
}
$arrObject[] = $object;
}
return $arrObject;
}
function super_unique($array)
{
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($result as $key => $value) {
if ( is_array($value) ) {
$result[$key] = super_unique($value);
}
}
return $result;
}
function merge_arrays($arr1, $arr2) {
$arr1 = (array)$arr1;
$arr2 = (array)$arr2;
$output = array_merge($arr1, $arr2);
sort($output);
return super_unique($output);
}
$array1 = array(
array("id" => "100", "name" => "muhammad"),
array("id" => "102", "name" => "ibrahim"),
array("id" => "101", "name" => "summayyah"),
);
$array1 = array_to_object($array1);
print "<h3>Your array 1</h3>";
print "<pre>";
print_r($array1);
print "</pre>";
$array2 = array(
array("id" => "100", "name" => "muhammad"),
array("id" => "103", "name" => "yusuf"),
);
$array2 = array_to_object($array2);
print "<h3>Your array 2</h3>";
print "<pre>";
print_r($array2);
print "</pre>";
$result = merge_arrays($array1, $array2);
print "<h3>Your desired output</h3>";
print "<pre>";
print_r($result);
print "</pre>";
it will output the following:
Your array 1
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => muhammad
)
[1] => stdClass Object
(
[id] => 102
[name] => ibrahim
)
[2] => stdClass Object
(
[id] => 101
[name] => summayyah
)
)
Your array 2
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => muhammad
)
[1] => stdClass Object
(
[id] => 103
[name] => yusuf
)
)
Your desired output
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => muhammad
)
[2] => stdClass Object
(
[id] => 101
[name] => summayyah
)
[3] => stdClass Object
(
[id] => 102
[name] => ibrahim
)
[4] => stdClass Object
(
[id] => 103
[name] => yusuf
)
)
Assignments:
Merge
Remove Duplicates
Sort by id
The good news is: Assigning temporary keys using id values does all of the hard work for you. No serializing is needed.
array_merge() joins the arrays together.
array_column() with a null 2nd parameter leaves the objects unmodified and id as the 3rd parameter assigns the temporary keys. Because arrays cannot have duplicate keys, duplicate objects are weeded out in this step.
Now that we have keys, ksort() avoids calling the more convoluted usort() to sort by id ascending.
Finally, call array_values() to re-index the resultant array (remove the temporary keys).
Code: (Demo)
$array1 = [
(object) ['id' => 100, 'name' => 'Muhammad'],
(object) ['id' => 102, 'name' => 'Ibrahim'],
(object) ['id' => 101, 'name' => 'Sumayyah']
];
$array2 = [
(object) ['id' => 100, 'name' => 'Muhammad'],
(object) ['id' => 103, 'name' => 'Yusuf']
];
$merged_keyed = array_column(array_merge($array1,$array2), NULL, 'id');
ksort($merged_keyed);
var_export(array_values($merged_keyed));
Alternatively, you can filter one of the arrays to remove duplicates, then merge them, then sort them. sort() will effectively order the rows by the id column because the rows have equal size and id is the element in first position.
Code: (Demo)
$result = array_merge($array1, array_udiff($array2, $array1, fn($a, $b) => $a <=> $b));
sort($result);
var_export($result);

Categories