I have an api and i want to parse data from it using php
That's the response
{
"success": true,
"data": [
{
"medicineId": 12,
"medicineName": "Abacavir"
},
{
"medicineId": 10,
"medicineName": "Alclometasone"
},
{
"medicineId": 15,
"medicineName": " Alectinib"
},
{
],
"message": "Successfully retrieved"
}
I want to list all medicine names
i tried this but it doesn't get the name just the success response
$age = file_get_contents('link');
$array = json_decode($age, true);
foreach($array as $key=>$value)
{
echo $key . "=>" . $value . "<br>";
}
You can easily list all medicine names with their id like this way by looping $array['data'] array. Let's do this way-
<?php
$age = '{"success":true,"data":[{"medicineId":12,"medicineName":"Abacavir"},{"medicineId":10,"medicineName":"Alclometasone"},{"medicineId":15,"medicineName":" Alectinib"}],"message":"Successfully retrieved"}';
$array = json_decode($age, true);
$medicine_names = [];
foreach($array['data'] as $key=>$value)
{
$medicine_names[$value['medicineId']] = $value['medicineName'];
}
print_r($medicine_names);
echo implode(' ', $medicine_names);
?>
Output:
Array (
[12] => Abacavir
[10] => Alclometasone
[15] => Alectinib
)
WORKING DEMO: https://3v4l.org/tBtaW
Related
I have this object in my session
name: "test",
is_feature: "0",
attributes: [
{
'5': "blue"
},
{
'7': "iOS"
}
],
cost: "2000",
I want to use attributes in foreach.some thing like below code:
foreach ($product->attributes as $attribute){
ProductAttributeValue::create([
'attribute_id' => $attribute->key, //like 5,7
'value' => $attribute->value //like blue,iOS
]);
}
Try this loop:
First you convert json to associative arrays like:
$productAttributes = json_decode($product->attributes, true);
and then
foreach ($productAttributes as $attributes) {
foreach ($attributes as $key => $attribute) {
ProductAttributeValue::create([
'attribute_id' => $key, // like 5,7
'value' => $attribute // like blue,iOS
]);
}
}
I hope it would helpful.
You use this:
$str = '{"name": "test", "is_feature": "0", "attributes": [{"5": "blue"},{"7": "iOS"}],"cost": "2000"}';
$arr = json_decode($str, true); // convert the string to associative array
foreach($arr["attributes"] as $attribute) {
$key = key($attribute); // get the first key as "5" of "7"
echo "key: $key and val: " . $attribute[$key]; // access the value as $attribute[$key] will give blue or ios
};
Live example: 3v4l
Reference: key
Here is a solution for you.
$strArr = [
'name'=>"test",
'is_feature'=> "0",
'attributes'=>[[5=> "blue"],[7=> "iOS"]],
'cost'=> "2000"
];
$str = json_encode($strArr);
$arr = (array) json_decode($str);
$att = (array) $arr['attributes'];
foreach($att as $val) {
foreach($val as $key=>$attributes) {
echo "key: ".$key." and val: " . $attributes . PHP_EOL;
}
};
Output:
key: 5 and val: blue
key: 7 and val: iOS
Hope this will help you
Hello I have a array like this.
$myarray = Array(
[0] => Array
(
[0] => Type
[1] => Brand
)
[1] => Array
(
[0] => Car
[1] => Toyota
)
)
I want result like this.
Type = Car
Brand = Toyota
So its mean From First Array "0" Value will be echo then from second array "0" Value will be shown.
Then From First array "1" value will be shown then from second array "1" Value will be shown.
Also I don't know how many array will be comes, So its need to be dynamic.
Any help Please?
You can try something like this (now i have tested it!):
foreach($myarray[0] as $titleKey=>$title) {
echo $title . " = ";
for($i = 1;$i<count($myarray);$i++) {
echo $myarray[$i][$titleKey] . ",";
}
echo "</br>";
}
Use array_combine for this
$myarray = [
['Type', 'Brand'],
['Car', 'Toyota']
];
list($fields, $values) = $myarray;
$output = array_combine($fields, $values);
echo json_encode($output, JSON_PRETTY_PRINT);
// {
// "Type": "Car",
// "Brand": "Toyota"
// }
But as you said, it could have more values than just the Toyota, so you'd have to do it like this
$myarray = [
['Type', 'Brand'],
['Car', 'Toyota'],
['Horse', 'Seabiscuit']
];
function first ($xs) { return $xs[0]; }
function rest ($xs) { return array_slice($xs, 1); }
$output = array_map(function ($values) use ($myarray) {
return array_combine(first($myarray), $values);
}, rest($myarray));
echo json_encode($output, JSON_PRETTY_PRINT);
// [
// {
// "Type": "Car",
// "Brand": "Toyota"
// },
// {
// "Type": "Horse",
// "Brand": "Seabiscuit"
// }
// ]
Note, this final solution assumes that the first array would contain the field names and the remaining arrays would have the values
Of course this works when more fields are added, too. No changes to the code are necessary.
$myarray = [
['Type', 'Brand', 'Origin'],
['Car', 'Toyota', 'Japan'],
['Horse', 'Seabiscuit', 'Kentucky']
];
function first ($xs) { return $xs[0]; }
function rest ($xs) { return array_slice($xs, 1); }
$output = array_map(function ($values) use ($myarray) {
return array_combine(first($myarray), $values);
}, rest($myarray));
echo json_encode($output, JSON_PRETTY_PRINT);
// [
// {
// "Type": "Car",
// "Brand": "Toyota",
// "Origin": "Japan"
// },
// {
// "Type": "Horse",
// "Brand": "Seabiscuit",
// "Origin": "Kentucky"
// }
// ]
I have 3 arrays for storing posts,comments, and likes.
These are the JSON strings:
//comments JSON (stores user and comment points)
$comments='[
{
"user": "5",
"points": "12"
},
{
"user": "2",
"points": "1"
},
{
"user": "3",
"points": "1"
}
]';
//likes(stores user and likes point)
$likes='[
{
"user": "1",
"points": 7
},
{
"user": "4",
"points": 4
},
{
"user": "3",
"points": 1
}
]';
//posts (stores user and post points)
$posts='[
{
"user": "1",
"points": "6"
},
{
"user": "3",
"points": "2"
},
{
"user": "2",
"points": "1"
}
]';
I convert these JSONs into arrays like this:
$comment_array = json_decode($comments,TRUE);
$like_array = json_decode($likes,TRUE);
$post_array = json_decode($posts,TRUE);
//echo '<pre>';
//print_r($comment_array);
//print_r($like_array);
//print_r($post_array);
//echo '</pre>';
Now, I'm trying to sum these points and save the result in a new array. It's not mandatory that a user should have entries in all the three arrays. It depends on whether a user has made a comment, post or like.
function mergeArrays($filenames, $titles, $descriptions) {
$result = array();
foreach ( $filenames as $key=>$name ) {
$result[] = array( 'filename' => $name, 'title' => $titles[$key], 'descriptions' => $descriptions[ $key ] );
}
return $result;
}
The above function can merge all the three arrays.
$merged= mergeArrays($comment_array, $like_array, $post_array);
echo '<pre>';
print_r($merged);
echo '</pre>';
However, each array after merging is stored as an index element.
How can I get a result something like this:
$result='[
{
"user": "1",
"points": "13"
},
{
"user": "2",
"points": "2"
},
{
"user": "3",
"points": "4"
},
{
"user": "4",
"points": "4"
},
{
"user": "5",
"points": "12"
}
]';
Considering your three arrays, this code will get you an array with: points, votes and diferent users.
Edit: Adding additional array and printing it to get the output desired by question.
$points = 0;
$uniqueUsers = array();
$votes = 0;
$users = 0;
$result = array();
//Comments
if (!empty($comment_array)) {
foreach ($comment_array as $item) {
if (!in_array($item['user'], $uniqueUsers)) {
array_push($uniqueUsers, $item['user']);
$result[$item['user']] = 0;
}
$votes ++;
$result[$item['user']] += $item['points'];
}
}
// Likes
if (!empty($like_array)) {
foreach ($like_array as $item) {
if (!in_array($item['user'], $uniqueUsers)) {
array_push($uniqueUsers, $item['user']);
$result[$item['user']] = 0;
}
$votes ++;
$result[$item['user']] += $item['points'];
}
}
// Posts
if (!empty($post_array)) {
foreach ($post_array as $item) {
if (!in_array($item['user'], $uniqueUsers)) {
array_push($uniqueUsers, $item['user']);
$result[$item['user']] = 0;
}
$votes ++;
$result[$item['user']] += $item['points'];
}
}
foreach ($result as $idUser=>$points) {
echo "\n";
echo "\n" . 'User: ' . $idUser;
echo "\n" . 'Points: ' . $points;
}
$results = array('users'=> count($uniqueUsers), 'votes'=>$votes, 'points'=> $points);
//print_r($results);
The solution using array_column, array_walk_recursive and array_values functions:
...
$comments = array_column($comment_array, 'points', 'user');
$likes = array_column($like_array, 'points', 'user');
$posts = array_column($post_array, 'points', 'user');
$list = [$comments, $likes, $posts];
$result = [];
array_walk_recursive($list, function($v, $k) use(&$result){
if (key_exists($k, $result)){
$result[$k]['points'] += $v;
} else {
$result[$k] = ['user' => $k, 'points' => $v];
}
});
$result = array_values($result);
print_r($result);
The output:
Array
(
[0] => Array
(
[user] => 5
[points] => 12
)
[1] => Array
(
[user] => 2
[points] => 2
)
[2] => Array
(
[user] => 3
[points] => 4
)
[3] => Array
(
[user] => 1
[points] => 13
)
[4] => Array
(
[user] => 4
[points] => 4
)
)
Do the following to get one array with summed points:
$collections = array(
'comments' => json_decode($comments,TRUE),
'likes' => json_decode($likes,TRUE);,
'posts' => json_decode($posts,TRUE),
);
$newArray = array();
foreach ($collections as $collection) {
foreach ($collection as $user) {
$newArray[$user->user] += $user->points;
}
}
There are two important points to make if you want to learn the "best" way to handle these types of operations.
Don't use iterated in_array() calls when isset() can be used instead. This is because isset() is much more efficient than in_array().
Use temporary keys to identify duplicate occurrences, then re-index your results when finished -- usually with array_values(), but this time I used array_multisort() to re-order the results AND re-index.
Code: (Demo)
$merged = array_merge(json_decode($comments, true), json_decode($likes, true), json_decode($posts, true));
$result = [];
foreach ($merged as $entry) {
if (!isset($result[$entry['user']])) {
$result[$entry['user']] = $entry;
} else {
$result[$entry['user']]['points'] += $entry['points'];
}
}
array_multisort(array_column($result, 'user'), $result);
// usort($result, function($a, $b) { return $a['user'] <=> $b['user']; });
// array_multisort() will outperform `usort()` in this case.
echo json_encode($result);
Output:
[{"user":"1","points":13},{"user":"2","points":2},{"user":"3","points":4},{"user":"4","points":4},{"user":"5","points":"12"}]
Decode each array and merge them together into a multi-dimensional array.
Iterate each subarray and determine if it is the first occurrence of the user. If so, retain the entire subarray. If not, only increase the points tally within that subarray.
When the loop is finished, sort by user ascending.
This is clean, direct, and readable.
Here's what I want to do in my php array to be exact json format below:
JSON
{
"suggestions": [
{ "value": "Alex - alex#email.com", "data": {"id": 1, "name": Alex } },
{ "value": "John - john#email.com", "data": {"id": 2, "name": John } },
{ "value": "Diaz - diaz#email.com", "data": {"id": 3, "name": Diaz } }
]
}
Query result in my php array:
array(
0 => array('id'=>'1' 'email'=>'alex#email.com', 'name'=>'Alex'),
1 => array('id'=>'2' 'email'=>'john#email.com', 'name'=>'John'),
2 => array('id'=>'3' 'email'=>'diaz#email.com', 'name'=>'Diaz')
);
Do you have any idea how will you make my php array to that JSON format way?
You can simply use json_encode(); function for that.
json_encode($array);
This should help you for your JSON format
foreach($query as $key => $val){
$json[$key]['value'] = $val['name']." - ".$val['email'];
$json[$key]['data']["id"] = $val['id'];
$json[$key]['data']["name"] = $val['name'];
}
echo json_encode($json);
foreach ($your_array as $key => $val) {
foreach ($val as $k => $v) {
if ($v == 'email') {
//get the value of 'email' key in 'value'
$newArr['suggestions']['value'] = current($v);
}
else {
//if value is not email push it in 'data' key
$newArr['suggestions']['data'] = $v;
}
}
}
//lastly encode the required array
echo json_encode($newArr);
When a form gets posted, I get some checkbox values like the below:
Array ( [chk0] => true ,
[chk1] => true,
[chk3] => true,
[chk1002] => on,
[chk1005] => on
)
Using PHP,How can I construct a JSON request like this by using the above variables?
"data":
[
{
"checkboxval": true,
"id": 0
},
{
"checkboxval": true,
"id": 1
},
{
"checkboxval": true,
"id": 3
},
{
"checkboxval": true,
"id": 1002
},
{
"checkboxval": true,
"id": 1005
}
]
Please note that my POST variables can have other form variables too, but all checkbox values will be named with the prefix "chk"
$output = array();
foreach ($input as $k => $v) {
$output[] = array(
'checkboxval' => !!$v,
'id' => preg_replace('!^chk!', '', $k),
);
}
header('Content-Type: application/json');
echo json_encode(array('data' => $output));
foreach ($_POST as $k => $v) {
$output[] = array(
'checkboxval' => ($v=='on'? true : ($v=='off' ? false : !!$v)),
'id' => preg_replace('!^chk!', '', $k),
);
}
header('Content-Type: application/json');
echo json_encode(array('data' => $output));
Credits to cletus who provided the basis for this code.
Have a look at the json_encode() php function. You'll have to massage your array a little to get the exact JSON format you're after.
Heres an example...
$_POST["chk1"] = "Hello";
$_POST["chk2"] = "World";
$jsonArray = array();
foreach($_POST as $key => $val){
if(preg_match("/chk/", $key)){
$jsonArray[$key] = $val;
}
}
$jsonArray = array("Data" => $jsonArray);
$json = json_encode($jsonArray);
echo "<pre>";
echo $json;
echo "</pre>";
Outputs this:
{"Data":{"chk1":"Hello","chk2":"World"}}
I haven't tested this yet, but maybe something like this:
$json = '"data": [';
$first = true;
foreach ($_POST as $k => $v){
if (preg_match('/^chk(\d+)$/', $k, $m)){
if ($first) $first = false; else $json .= ", ";
$json .= sprintf('{ "checkboxval" : %s, "id" : %s }', ($v && $v != "off") ? "true" : "false", $m[1]);
}
}
$json .= ']';