php array to json array (using sendgird) - php

I would like to use a php array in this example rather than have to hard code the array. How would I use a php to replace this json example?
Here the working code with the json array:
$json_string = array(
'to' => array(
'example1#sendgrid.com', 'example2#sendgrid.com'
),
'category' => 'test_category'
);
But I need to replace the 'to' values with my own php array. I tried this but it doesn't work:
$myEmails[] = array('emailOne#gmail.com','email2#gmail.com');
$json_string = array(
'to' => $myEmails, /// DOES NOT WORK
'category' => 'test_category'
);
What code for the json could I use to add my own php array values here? In short I am trying to send multiple emails using sendgrid but I thought this might work but its not.

Just get rid of the square braces [] after $myEmails, and everything should work:
<?php
$myEmails = array('emailOne#gmail.com','email2#gmail.com');
$json_string = array(
'to' => $myEmails, /// DOES NOT WORK
'category' => 'test_category'
);
var_dump($json_string);
?>

Related

Remove names from Json Encode

Currently my JSON outputs from the following PHP:
$data['products'][] = array(
'product_id' => $result['product_id'],
'thumb' => $image,
'name' => $result['name'],
'description' => $desc,
'price' => $price,
'special' => $special,
'tax' => $tax,
);
And with this ($products = json_encode ($data['products']);) produces the following:
[{"product_id":"28",
"thumb":"x",
"name":"name",
"description":"abc",
"price":"$123.00",
"special":false,
"tax":"$100.00"}]
Is it possible to delete the names without modifying the php "$data['products'][] = array();"? I am trying to achieve:
["28",
"x",
"name",
"abc",
"$123.00",
false,
"$100.00"]
First time ever using JSON encode so any other advice would be awesome!
You can use array_map to loop thru your array and use array_values as callback function to convert the associative array to simple array
$arr = array_map('array_values', $data['products'] );
$products = json_encode ($arr);
This will result to:
[["28","x","name","abc","$123.00",false,"$100.00"]]
Live Example
You can use array_values to get the values of the first/only entry in $data['products'], and then encode that:
$json = json_encode(array_values($data['products'][0]));
That produces
["28","x","name","abc","$123.00",false,"$100.00"]
Live Example

PHP: How do I echo the results of this array?

$header_content = array();
$header_content['pageone'][] = array(
'image' => 'photo-one.png',
'desc' => "One. Some text here.",
);
$header_content['pagetwo'][] = array(
'image' => 'photo-two.png',
'desc' => "Two. Some text here.",
);
I do not want to echo the entire array, just certain parts when called... like $header_content['pageone']['image'], except this doesn't work... How do you go about echoing parts of an array?
I have searched but it's all a little confusing right now for me. Thanks.
Define it like -
$header_content['pagetwo'] = array(
'image' => 'photo-two.png',
'desc' => "Two. Some text here.",
);
The keys are different pageone, pagetwo. No need of that extra index i think. And then access it - echo $header_dontent['pagetwo']['image'];
For printing array values, you can use :
print_r function
Example : print_r($array)
Specific key data can be accessed through : print_r($array[$key])
OR
var_dump function
Example : var_dump($array)
Specific key data can be accessed through : var_dump($array[$key])
use it like $header_content['pageone'][0]['image']
Since
$header_content['pageone'][] = array();
[] appends an element at the end of an array.

Formatting JSON in PHP

I am trying to build some JSON on the in PHP. I am brand new to PHP and know very little about it. Currently, I have the following:
$json = '{"content":{"person":{"name":"$name", "email":"$email"}, "title":"$subject", "description": { "body": "$details" }}}';
$name, $email, $subject, and $details are all variables that have been defined previously. If I print out $json using the code above, I get the following:
{"content":{"person":{"name":"$name", "email":"$email"}, "title":"$subject", "description": { "body": "$details" }}}'
In other words, my variables didn't replace the placeholders in the string. How do I build some JSON using variables as key values?
Thank you!
In PHP, double quotes and single quotes do different things; you can only use variables inline within strings if you use double quotes:
$test = 'world';
echo 'Hello $test!'; // Prints: Hello $test!
echo "Hello $test!"; // Prints: Hello world!
If you use double quotes to surround your json string, you'd need to escape all the double quotes that you have inside it:
$json = "{\"content\":{\"person\":{\"name\":\"$name\", \"email\":\"$email\"}, \"title\":\"$subject\", \"description\": { \"body\": \"$details\" }}}";
Alternative Method
NB: Are you familiar with PHP arrays? PHP has the function json_encode that converts arrays into JSON strings - doing that might make your code easier (especially if your json string is going to get larger / more complex at any point)
$json = json_encode(array
(
"content" => array
(
"person" => array
(
"name" => $name,
"email" => $email
),
"title" => $subject,
"description" => array
(
"body" => $details
)
)
));
Either of these solutions should give $json the value you expect
Hope this helps :) x
As mentioned in the comments, the best way would be to build up your data into the structure that you want and use json_encode to fix it.
The reason that you particular string is not replacing the variables is because it is enclosed by ' instead of "
$json = "{\"content\":{\"person\":{\"name\":\"$name\", \"email\":\"$email\"}, \"title\":\"$subject\", \"description\": { \"body\": \"$details\" }}}'\";
http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing
$content = json_encode(array(
'content' => array(
'person' => array(
'name' => $name,
'email' => $email,
'title' => $subject,
'description' => array(
'body' => $details
)
)
)
);
echo $content;
The documentation is always very helpful, check out the ones for strings, here it will explain how you can and cannot use variables in single quoted or double quoted strings.
Documentation on Strings
An easier solution is to use an array and json_encode it which will output what you have in your question:
<?php
$array = array(
'content' => array(
'person' => array(
'name' => $name,
'email' => $email,
),
'title' => $subject,
'description' => array(
'body' => $details,
),
),
);
$json = json_encode($array);

Convert PHP Array to String?

I'm working with this PHP Array and I'm trying to convert it into a string:
$args=shortcode_atts( array(
'setting' => 'value',
'setting' => 'value',
'setting' => 'value',
), $atts);
The result should look like this:
' "setting":"value","setting":"value" '
I'm not sure how to loop through this? I've also noticed a lot of docs online that include the comma at the end of the last array item - is this ok or should I be in the habit of not including the comma?
I believe that you are looking for json encoded data:
$json = json_encode($args);

pushing and apending arrays into an associative array in php

How do I push arrays inside the "adjacencies" key value pair that should have an encapsulated array holding the "arrays" (ie. array(("nodeTo" => "$to"),("nodeTo" => "$to"))) without overwriting them and appending them similiar to "+=". also the push into the key "adjacencies" doesnt seem to pick up the value.
$node[] = array(
"adjacencies" => array(), //inside this array should go all the arrays seprated by commas.
"data" => array(
"color" => $color1,
"type" => $type1
);
// this push doesnt seem to detect the adjacencies value and doesnt really push the array inside of the container array. I also tried $node["adjacencies"][]=array("nodeTo" => "$to"); but it didnt work
$node["adjacencies"]=array("nodeTo" => "$to");
}
If you want multiple arrays within 'adjacencies', append them to the end of the array:
$node[0]['adjacencies'][] = array("nodeTo" => "$to");
Granted, you'll need to know which $node index to work with (if there are multiple nodes).
Edit:
After reading the comments, it looks like the OP's desired array structure is this:
$node = array(
'adjacencies' => array(),
'data' => array(
'color' => $color1,
'type' => $type1,
);
);
Thus, to append additional nodes to the adjacencies array, you can do this:
$node['adjacencies'][] = array('nodeTo' => "$to");
By the way you use $node in the second statement I think you meant:
$node = array(
not:
$node[] = array(
// ^^
Then you can push the array by doing:
$node['adjacencies'][] = array('nodeTo' => $to);

Categories