PHP String of arrays to Array - php

I have a json that is mapped on an object. The json looks like above:
{
"employeeId": "1",
"firstName": "John",
"lastName": "Doe",
"departments": [
{
"fieldName": "department",
"fieldValue": "[dep1, dep2]"
}
]
}
I need to take data from "fieldValue" and put it into an array.
json_decode doesn't work for me since the values inside are not quoted. It would be very helpful if I had it like "fieldValue": "[\"dep1\",\"dep2\"]", but I cannot control how I receive it. Does somebody has some suggestions on how to make an array out of a string that looks like that?

Not sure that it is good variant, but you can use json_decode function two time:
$json = '{
"employeeId": "1",
"firstName": "John",
"lastName": "Doe",
"departments": [
{
"fieldName": "department",
"fieldValue": "[dep1, dep2]"
}
]
}';
$decodedJson = json_decode($json);
$fieldValue = json_decode(strtr($decodedJson->departments[0]->fieldValue, array(
'[' => '["',
']' => '"]',
',' => '","'
)));
var_dump($fieldValue);

$var = "[dev1, dev2]";
$keywords = preg_split('/[\[+\]]/', $var);
$keywords[1] will be your answer.
Then, you can split the $keywords[1] variable into an array using str_split()

Related

Creating multi dimensional arrays, and handeling same key name issues for json_encode

I am trying to adhere to an integration requirement of having multiple items with the same key names, including its meta data into a main array to properly json_encode.
I have tried splitting out and joining arrays, array_push. The only workable solution I have is to manually build this part of the json package. Any help would be greatly appreciated.
Here is a sample of what I am struggling with:
$message_pack["Header"]["Sequence"] = 'TEST1';
$message_pack["Header"]["TC"] = "1";
$message_pack["ItemDetail"]["ItemName"] = "Item1";
$message_pack["ItemDetail"]["ItemCode"] = "123";
$message_pack["ItemDetail"]["Itemname"] = "Item2";
$message_pack["ItemDetail"]["ItemCode"] = "234";
$json_msg = json_encode($message_pack);
This will obviously only take the last value passed to the matching key name.
I need to adhere to this json format:
{
"Header": {
"Sequence": "TEST1",
"TC": "1",
},
"ItemDetail": [{
"ItemName": "Item1",
"ItemCode": "123" }
{ "ItemName": "Item2",
"ItemCode": "234" }]
}
You need to make "ItemDetail" an array, else you'll overwrite $message_pack["ItemDetail"]["Itemname"] and $message_pack["ItemDetail"]["ItemCode"]:
<?php
$message_pack["Header"]["Sequence"] = 'TEST1';
$message_pack["Header"]["TC"] = "1";
$message_pack["ItemDetail"][] = ["ItemName" => "Item1", 'ItemCode' => 123];
$message_pack["ItemDetail"][] = ["ItemName" => "Item2", 'ItemCode' => 234];
$json_msg = json_encode($message_pack, JSON_PRETTY_PRINT);
echo ($json_msg);
will output:
{
"Header": {
"Sequence": "TEST1",
"TC": "1"
},
"ItemDetail": [
{
"ItemName": "Item1",
"ItemCode": 123
},
{
"ItemName": "Item2",
"ItemCode": 234
}
]
}

Extracting json object from array

I am using php/Laravel and i have a response from an API that returns the following format in my controller:
[
{
"id": "474",
"room_id": "14",
"user_id": "20",
"name": "121001.webm",
"fname": "",
"status": "0",
"date_recorded": "October 17 2018 07:18:51",
"size": "396135",
"is_public": "0",
"allow_download": "0",
"privatekey": "",
"duration": "0",
"record_path": "https:example/url/test.mp4",
"record_url": "https:example/url/test.mp4"
}
]
I believe this is an array inside of the array is the json object i want the data from, so for example I want the record id.
I have used these solutions with no luck :
$response->record_url;
$response[0]->record_url;
also tried to encode or decode the $response
Any help would be greatly appreciated
In JSON string, you have and array with one element being an object.
Now, depending on how you're decoding it, you'll get in PHP and array with stdClass object, or array with associative array inside.
//this will return array with stdClass object
$data = json_decode($json);
echo $data[0]->record_url;
//this will return array with associative array
$data = json_decode($json, true);
echo $data[0]['record_url'];
Working code: https://3v4l.org/TJNQ1
Try this code
var_dump(json_decode($response)->record_url);
Please refer the below program and respective output:
$json = '[
{
"id": "474",
"room_id": "14",
"user_id": "20",
"name": "121001.webm",
"fname": "",
"status": "0",
"date_recorded": "October 17 2018 07:18:51",
"size": "396135",
"is_public": "0",
"allow_download": "0",
"privatekey": "",
"duration": "0",
"record_path": "https:example/url/test.mp4",
"record_url": "https:example/url/test.mp4"
}
]';
$array1 = json_decode($json, false);
echo $array1[0]->id //This will print the value of id which is 474.
$array2 = json_decode($json, true);
echo $array2[0]['id'] // This will also print th evalue of id which is 474.
The second parameter of the function json_decode is boolean when TRUE, returned objects will be converted into associative arrays.
Thanks

Best Practice To Convert Regular Array To Associative Using An Attribute as a Key?

Let's say I have the following array
[
{
"id": "16",
"name": "dog",
},
{
"id": "17",
"name": "cat",
},
{
"id": "18",
"name": "mouse",
}
]
I want to use a specific attribute, id as the key for the array. I could do this:
$someArray = [
["id" => "16", "name" => "dog"],
["id" => "17", "name" => "cat"],
["id" => "18", "name" => "mouse"]
];
$newArray = [];
foreach ($someArray as $currItem)
{
$newArray[$currItem["id"]] = $currItem;
}
Then I would have this (the desired outcome)
{
"16": {
"id": "16",
"name": "dog"
},
"17": {
"id": "17",
"name": "cat"
},
"18": {
"id": "18",
"name": "mouse"
}
}
My question is: is there a better way to do this? Do I really have to loop through every item just to redefine my array ever so slightly?
I seem to have found a solution using information from Rizier123's comment and this thread: PHP Change Array Keys
As far as I can tell array_column is only going to give me an array of ids, so I need to use it with array_combine and array_values. Please don't be afraid to post if you have a better answer
$someArray = [
["id" => "16", "name" => "a"],
["id" => "17", "name" => "b"],
["id" => "18", "name" => "c"]
];
$newArray = array_combine(array_column($someArray, "id"), $someArray);
You beat me to the answer but I might contribute a little anyway...
I'm not sure where your original array is coming from, but if you are decoding JSON, then you can provide a second param to force objects to be converted to associative arrays
$contents = trim(file_get_contents("/home/jaith/foo/foo.json"));
$arr = json_decode($contents, TRUE); // note the second parameter
$v = array_combine(array_column($arr, "id"), $arr);
var_dump($v);
EDIT:
If you can tolerate your output array having objects, this might also work:
$contents = trim(file_get_contents("/home/jaith/foo/foo.json"));
$arr = json_decode($contents);
$v = array_combine(
array_column(
array_map(
function($item) { return (array)$item; },
$arr
),
"id"
),
$arr
);
var_dump($v);
Keep in mind though that performance could become a concern for very very large arrays. This is doing a lot of array munging.

Insert a Variable inside simple quotation marks PHP

How i can use a variable ($_REQUEST('subject')) inside simple quotation marks.
This is my code:
<?php
$uri = 'https://mandrillapp.com/api/1.0/messages/send.json';
$postString = '{//i can't quit this quotation mark
"key": "myapi",
"message": {
"html": "this is the emails html content",
"subject": "$_REQUEST['subject'];",//this dont work
"from_email": "email#mydomain.com",
"from_name": "John",
"to": [
{
"email": "test#hotmail.com",
"name": "Bob"
}
],
"headers": {
},
"auto_text": true
},
"async": false
}';
?>
That's JSON! Use json_encode and json_decode!
$json = json_decode ($postString, true); // true for the second parameter forces associative arrays
$json['message']['subject'] = json_encode ($_REQUEST);
$postString = json_encode ($json);
Although, it looks like you could save a step and yourself some trouble if you just build $postString as a regular php array.
$postArr = array (
"key" => "myapi",
"message" => array (
"html" => "this is the emails html content",
"subject" => $_REQUEST['subject'],
"from_email" => "email#mydomain.com",
"from_name" => "John",
"to" => array (
array (
"email" => "test#hotmail.com",
"name" => "Bob"
)
),
"headers" => array (),
"auto_text" => true
),
"async" => false
);
$postString = json_encode ($postArr);
change "subject": "$_REQUEST['subject'];" to "subject": "' . $_REQUEST['subject'] . '"
Try this:
$postString = '{
"key": "myapi",
"message": {
"html": "this is the emails html content",
"subject": "'.$_REQUEST['subject'].'", // Modify this way
"from_email": "email#mydomain.com",
"from_name": "John",
....
.....
}';

Accessing JSON encoded PHP Array in jQuery

I have an PHP Array which is formatted in the following format :
$jsonArray = array(
"facebook" => array("user" => "8", "user_id" => "10", "user_post" => "6"),
"twitter" => array("user" => "8", "user_id" => "10", "user_post" => "6")
);
I've then done the following so I can access the array
echo "<script type='text/javascript'>window.MyArray = ".json_encode($jsonArray).";</script>";
And to access the array I tried the following
alert(window.MyArray['facebook'][0]['user']);
yet that's seemed to fail, any directions?
window.MyArray['facebook'][0]['user']
--------------------------^^^
Why do you need [0] here?
Use this:
window.MyArray['facebook']['user']
MyArray gives this:
{
"facebook": {
"user": "8",
"user_id": "10",
"user_post": "6"
},
"twitter": {
...
}
}
MyArray['facebook'] results in the following array:
{
"user": "8",
"user_id": "10",
"user_post": "6"
}
Therefore, MyArray['facebook']['user'] results in 8.
try this way:
alert(window.MyArray.facebook.user);
it will work
You are passing the json as a string, you need to convert it to an object. To do that you can use http://www.json.org/js.html

Categories