How to put array to obj in php? - php

I have an json obj:
$response["data"][] = array("ID" => $comment["ID"]);
I put to new obj like this:
array_push($response["username"],"abc");
and it return like this:
{"data":[{"ID":"2106"}],"username":"123"}
but I want to like this:
{"data":[{"ID":"2106","username":"123"}]}
How can I do it?

Maybe you mean this:
{"data":[{"ID":"2106", "username":"123"}]
BTW you need
array_push($response["data]["username"],"abc");

Maybe you want:
$response["data"][] = array("ID" => $comment["ID"], 'username' => '123');
Please note that you can always simplify your code to make it more readable by creating variables.
$row = array(
'ID' => $comment['ID'],
'username' => '123'
);
$response['data'][] = $row;

Related

Using Object instead of Array

i'm not good at using objects. And i'm working on using objects instead of arrays.
I have a code as array
$jsonData['overstockid'][] = $productid;
How can i write this as object ?
I defined jsonData
$jsonData = new \stdClass();
i know i can write $jsonData->overstockid
Set the overstockid property to an array, and then add to it:
$jsonData->overstockid = array();
$jsonData->overstockid[] = $productid;
A quick but nasty workaround to convert an array to an object is to use json_encode() and json_decode().
Example
$array = array(
'id' => 123,
'sub_id' => 456,
'gender' => 1,
'name' => 'John Doe',
'age' => 960,
);
$object = json_decode(json_encode($array));
Hope this helps.

Retrieve single value from this php array

I have this php array $result2 that looks like this.
[
(int) 0 => object(stdClass) {
id => (int) 1
username => 'asd'
password => '123'
fullname => 'asd'
email_addr => 'asd#gmail.com'
}
]
From $result2, I want to have a $json_result that looks like this;
[{"email_addr":"asd#gmail.com"}]
I tried
$emailAddress[] = ['email_addr' => $result2['email_addr'] ];
echo json_encode($emailAddress);
However, the error I get is this;
Notice (8): Undefined index: email_addr
[APP/Controller\DeptUsersController.php, line 126]
The output is like this which is wrong;
[{"email_addr":null}]
What is the correct way?
Read carefully (int) 0 => object(stdClass) It's an object, and this object is an element with index 0 of an array. So:
$emailAddress[] = ['email_addr' => $result2[0]->email_addr ];
it's object you can't show value if using $result2['email_addr'] you should using this $result2->email_addr method
You have an object of type stdClass so you can't access directly to the field email_addr. Try this code:
$mObject = new stdClass();
$mObject = $result2[0];
$emailAddress[] = ['email_addr' => $mObject->email_addr ];
echo json_encode($emailAddress);
This should fix your error
Try this:
$emailAddress[] = ['email_addr' => $result2[0]->email_addr ];
You can use array_intersect_key :
$wanted = ["email_addr"=>""];
$data = [
"id" => 1,
"username" => 'asd',
"password" => '123',
"fullname" => 'asd',
"email_addr" => 'asd#gmail.com',
];
$result = array_intersect_key($wanted, $data);
var_dump($result);
It useful when you need one or more key to find. It more saving time

Dynamic creation of a multidimensional array in php

I am fetching for some values from the database, and i need to dynamicaly create a multidimensional array to look like this:
$found_data =
array(
array('2011-11-02' => 'Mobile'),
array('2011-11-02' => 'Mobile'),
array('2011-11-04' => 'Mobile'),
array('2011-11-08' => 'Desktop'),
array('2011-11-08' => 'Mobile'),
array('2011-11-08' => 'Mobile'),
array('2011-11-08' => 'Mobile'),
array('2011-11-15' => 'Mobile'),
array('2011-11-18' => 'Mobile'),
array('2011-11-21' => 'Desktop'),
array('2011-11-23' => 'Mobile'),
array('2011-11-28' => 'Desktop'),
array('2011-11-30' => 'Mobile')
);
I am thinking something in the lines of:
$found_data = array();
while($last_30_days_fetch = mysql_fetch_assoc($last_30_days_result))
{
$hit_date = $last_30_days_fetch['hit_date'];
$hit_device = $last_30_days_fetch['hit_device'];
array_push($found_data, array($clean_date=>$hit_device));
}
However the above code, does not work as intended. Any ideas?
// Thanks
You are using a variable $clean_date that is not defined. Check your error_reporting level it should report this (undefined variable).
PHP allows the use of the [] syntax to append elements to an array.
$found_data = array();
while($last_30_days_fetch = mysql_fetch_assoc($last_30_days_result))
{
$found_data[] = array(
$last_30_days_fetch['hit_date'] => $last_30_days_fetch['hit_device']
);
}
$found_data = array();
while($last_30_days_fetch = mysql_fetch_assoc($last_30_days_result))
{
$found_data[] = array($last_30_days_fetch['hit_date']=>$last_30_days_fetch['hit_device']);
}
why over complicate it or as Dan says put it into a single array there's no need for a multi array unless there's additional data you're not telling us about
Could you not just use:
$array[$hit_date] = $hit_device

PHP - trying to make a JSON-like array and getting confused

I am using PHP and trying to create an array that looks something like this:
{
"aps" : {
"alert" : "Hey"
},
"custom_control" : {
"type" : "topic_comment",
"object":{
"topic_id":"123",
"topic_section":"test"
"plan_id":"456"
}
}
}
So far I have something like
$message = array('aps'=>array('alert'=>$some_variable));
but I am getting confused how I can put the values for "custom_control" into this array after that. Could anyone please advise how to do that from my existing php?
Thanks!
Is this what you mean?
<?php
$some_variable = "Hey";
$myArray = array(
"aps" => array(
"alert" => $some_variable
),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
);
?>
Here is an easy way to discover what you need to do.
Create your JSON object.
Use it as input to the json_decode function.
Use the output of this as the input to var_export()
So supposing you assigned your JSON to $json_object, then use:
var_export(json_decode($json_object, true));
If you are more comfortable building the object in JSON you can use the JSON parser included in php. Also, JSON defines Javascript objects, not arrays (although you can define arrays in JSON with something like {myArray : [1,2,3]}
Try this if you want though:
http://php.net/manual/en/function.json-decode.php
If you've already created your initial message array (per your question), you would then do something like this.
$message["custom_control"] = array(
"type" => "topic_comment",
"object" => array(
"topic_id" => "123",
"topic_section" => "test",
"plan_id" => "456"
)
)
You can create whatever nodes you needs inside of $message this way.
What you are trying to create is not an array, but rather an object.
Try to not build it as an array but an object.
$obj = new stdClass();
$obj->aps = new stdClass();
$obj->aps->alert = 'Hey';
$obj->custom_control = new stdClass();
$obj->custom_control->type = 'topic_comment';
$obj->custom_control->object = new stdClass();
$obj->custom_control->object->topic_id = '123';
$obj->custom_control->object->topic_section = 'test';
$obj->custom_control->object->plan_id = '456';
$json = json_encode($obj);
$array = array();
$array['aps'] = "alert";
$array['custom_control'] = array();
$array['custom_control']['type'] = "topic_comment";
$array['custom_control']['object'] = array('topic_id' => '123',
'topic_section' => 'test',
'plan_id' => '456');
i think you need something like this:
$message =array( "aps" =>array("alert"=>"Hey"),
"custom_control" => array(
"type" => "topic_comment",
"object" => array(
"topic_id"=>"123",
"topic_section"=>"test",
"plan_id"=>"456"
)
)
);

An array of MySQL results...

What am I doing wrong here?
I am attempting to return a json object and I can't seem to get past the array... I've built hundreds of regular array and returned them as a json object but I am having a hard time wrapping my head around this one.
$rows = array();
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] = $rows[ "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate ];
$i++;
}
It looks like you mean to define an array for $post_array[$i] = .... Like this?
$post_array[$i] = array(
"id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate,
);
(Also, I just took the liberty to respace that a little for readability.)
To convert your array to JSON, pass it to json_encode().
Update: Oh, before you ask about it, I just noticed I added a comma out of habit after the last item in the array. It looks like it's out of place, but it's actually fine to have it there when defining arrays. It doesn't serve any special purpose, but it allows you to copy/paste/remove lines from the array without having to worry about whether or not to add/remove a trailing comma.
As an aside, you don't have to manually increment a numeric array index $i. If you just do this:
$post_array[] = array(...);
it will automatically assign the next available numeric index.
Do you mean do be doing something like this:
$post_array = array();
$i = 0;
$result = mysql_query(" SELECT * FROM forum_posts WHERE permalink = '$permalink' AND LOWER(raw_text) LIKE '%$str%' " );
while($row = mysql_fetch_assoc($result))
{
$post_array[$i] =array( "id" => htmlentities($row["id"]),
"post_content" => htmlentities($row["content"]),
"author" => $row["author"],
"last_updated" => $row["last_updated"],
"author_id" => $row["author_id"],
"editing_author" => $row["editing_author"],
"date" => $outputQuoteDate );
$i++;
}
Then you can simply use json_encode to encode your array as json.
e.g.
echo json_encode($post_array);
You can't build an array the way you were with $rows[...], you need to use array. Also, instead of managing the ordinals for your array, you can just use array_push

Categories