Create a another associative array inside existing array - php

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>";
?>

Related

Get data from inside array in 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
)
)

How to structure an array in php for specific use

Am trying to arrange data's that i retrieved from database in an an array, but it can't get the array structure the way i want it to look like.
<?php
$ujahdb->prepare("SELECT * FROM productcomment WHERE code = :code");
$ujahdb->bind(":code", $GetProductCode);
$ujahdb->execute();
$productComments = $ujahdb->getAll();
$ujahdb->free();
if(!empty($productComments)){
//require_once('ini.config/ProductStarRating.php');
$rateing['comments'] = '';
foreach($productComments as $com){
$rateing[]['name'] = $com->commenter_name;
$rateing['star'] = $com->comment_rate;
print_r($rateing);
}
}
?>
This is the array am getting
Array ( [comments] => [0] => Array ( [name] => Peter ) [star] => 3 )
Array ( [comments] => [0] => Array ( [name] => Jonh ) [star] => 2 [1]
=> Array ( [name] => Peter ) )
I need something like this-
Array([comments] => Array([0] => Array([name] => Peter [star] => 3)
[1] => Array([name] => Jonh [star] => 2)))
Any idea how to make this right?
I think this should do it
<?php
$ujahdb->prepare("SELECT * FROM productcomment WHERE code = :code");
$ujahdb->bind(":code", $GetProductCode);
$ujahdb->execute();
$productComments = $ujahdb->getAll();
$ujahdb->free();
if(!empty($productComments)){
//require_once('ini.config/ProductStarRating.php');
foreach($productComments as $com){
$rateing = [];
$rateing["comments"] = [
"name" => $com->commenter_name,
"star" => $com->comment_rate,
];
print_r($rateing);
}
}
?>

How to parse array elements?

I tried to parse a string array using the code below but the required data never printed! could any one tell me how to fix it ?Thanks
$data Array structure :
Array
(
[js] => Array
(
[total_items] => 20
[max_page_items] => 2
[selected_item] => 0
[cur_page] => 0
[data] => Array
(
[0] => Array
(
[tmp] => 1
[name] => mango
[abc] => abcd4 http://mysite/items/1234
[number] => 1123
[itemCategory_title] => fruits
[logo] => 2123.png
[itemCategory_id] => 90
)
[1] => Array
(
[tmp] => 0
[name] => cherry
[abc] => abcd4 http://mysite/items/1235
[number] => 1124
[itemCategory_title] => fruits
[logo] => 2124.png
[itemCategory_id] =>
)
)
)
[text] => no error
)
php code:
<?
$code2 = stripslashes($_POST['outputtext']);
$data = json_decode($code2);
foreach( $data as $item ) {
echo $item['tmp'];
echo $item['name'];
echo $item['abc'];
echo $item['number'];
echo $item['itemCategory_title'];
echo $item['log'];
echo $item['itemCategory_id'];
}
?>
It should be:
foreach ($data['js']['data'] AS $item)
because the array is nested several levels down in $data.
Note that you need to call json_decode($code2, true) to get an associative array like that. By default, it returns an object, not an array, so you would do:
foreach ($data->js->data as $item) {
echo $item->tmp;
echo $item->name;
...
}

how to clean the extra elements from array

this is my php code.
while($fetchRes=mysql_fetch_assoc($query9)) {
$rows[] = array(
array('iso'=>$staff_id,
'name'=>$name,
'iso3'=>$last_name,
'numcode'=>$email
),);
}
echo '<pre>';
$rows=print_r($rows);
echo '</pre>';
after running this code i am getting the following output.
Array (
[0] => Array (
[0] => Array ( [id] => 008 [name] =>
dev [last_name] => abc [email] => abc#gmail.com ) )
[1] => Array ( [0] => Array ( [name] => 7002
[name] => Sheela [lastname] => Mbhhh [email] => 7002#iem.com ) )
but problem is that i want the following type of array
array(
array('id'=>'008 ',
'name'=>'dev ',
'last_name'=>'abc ',
'email'=>'abc#gmail.com',
),
array('id'=>'AL',
'name'=>'Albania',
'last'=>'ALB',
'email'=>'8',
)
means i dont want the extra things in my array like Array (
[0] =>, Array (
[1] =>
Then why do you use an array inside another array? ($rows[] = array(array(...)
Try this:
while($fetchRes=mysql_fetch_assoc($query9)) {
$rows[] = array(
'iso' => $staff_id,
'name' => $name,
'iso3' => $last_name,
'numcode' => $email
);
}

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);

Categories