Separate Array objects on key bases - PHP - php

I have an Array containing sub-sets of data as following:
"options":[
{
"id":"13",
"option_name":"M",
"option_id":"1",
"label":"Size"
},
{
"id":"13",
"option_name":"L",
"option_id":"1",
"label":"Size"
},
{
"id":"13",
"option_name":"BLUE",
"option_id":"1",
"label":"Color"
},
{
"id":"13",
"option_name":"GREEN",
"option_id":"1",
"label":"Color"
}
]
I want to loop into this array and separate objects/subsets based on key label. As following:
"options":[
{
"label":"Size",
"optionsArray":[
{
"id":"11",
"option_name":"XL",
"option_id":"1",
"label":"Size",
},
{
"id":"12",
"option_name":"L",
"option_id":"1",
"label":"Size",
}
]
},
{
"label":"Color",
"optionsArray":[
{
"id":"11",
"option_name":"BLUE",
"option_id":"1",
"label":"Color",
},
{
"id":"12",
"option_name":"GREEN",
"option_id":"1",
"label":"Color",
}
]
}
]
How can i achieve this with PHP?
As this post is already full of code, stackoverflow wouldn't let me paste my current try of code, so i will try to paste simple structure as plain text.
$keys = array_keys(current($options));
$len = count($options);
foreach($keys as $key){
// Access the key first
for($i=0;$i<$len; $i++){
// access the row later
echo $array[$i][$key];
}
}

I'd do it like that:
$result = [];
foreach ($options as $option) {
if (!isset($result[$option['label']])) {
$result[$option['label']] = [
'label' => $option['label'],
'optionsArray' => []
];
}
$result[$option['label']]['optionsArray'][] = $option;
}
$result = array_values($result);

<?php
// Decode the JSON (true for using associative arrays)
$array = json_decode($json, true);
// Initialize three arrays
$colors = [];
$sizes = [];
$unknown = [];
// Loop and seperate them using a switch
foreach ($array['options'] as $o) {
if (! isset($o['label'])) {
trigger_error('label not in object', E_USER_WARNING);
}
switch($o['label']) {
case 'Size':
$sizes[] = $o;
break;
case 'Color':
$colors[] = $o;
break;
// Put all malformed objects into this array
default:
$unknown[] = $o;
}
}
// You can now easily build your new array
$output = ['options' => [
['label' => 'Size', 'optionsArray' => $sizes],
['label' => 'Color', 'optionsArray' => $colors]
]];

Related

PHP - Check if value exists in array but only for specific key

I have an array and I am checking if a value exists in the array using in_array(). However, I want to check only in the ID key and not date.
$arr = ({
"ID":"10",
"date":"04\/22\/20"
},
{
"ID":"20",
"date":"05\/25\/20"
},
{
"ID":"32",
"date":"07\/13\/20"
});
So in this example, the condition should not be met since 25 exists in date, but not in ID.
if (in_array("25", $arr)) {
return true;
}
To directly do this, you need to loop over the array.
function hasId($arr, $id) {
foreach ($arr as $value) {
if ($value['ID'] == $id) return true;
}
return false;
}
If you need to do this for several IDs, it is better to convert the array to a map and use isset.
$map = array();
foreach ($arr as $value) {
$map[$value['ID']] = $value;
// or $map[$value['ID']] = $value['date'];
}
if (isset($map["25"])) {
...
}
This will also allow you to look up any value in the map cheaply by id using $map[$key].
For versions of PHP (>= 5.5.0), there is a simple way to do this
$arr = ({
"ID":"10",
"date":"04\/22\/20"
},
{
"ID":"20",
"date":"05\/25\/20"
},
{
"ID":"32",
"date":"07\/13\/20"
});
$searched_value = array_search('25', array_column($arr, 'ID'));
Here is documentation for array_column.
You can also check it by array_filter function:
$searchId = '25';
$arr = [[
"ID" => "10",
"date" => "04\/22\/20"
],
[
"ID" => "25",
"date" => "05\/25\/20"
],
[
"ID" => "32",
"date" => "07\/13\/20"
]];
$items = array_filter($arr, function ($item) use ($searchId) {
return $item['ID'] === $searchId;
});
if (count($items) > 0) {
echo 'found';
};

Combine an array using two endpoints

I'm parsing through and array mapping that I would like to only pull in the media_url's, but now I also need the permalinks - How would I be able to combine the two below and then include the permalink in the foreach loop?
$mediaUrls = array_map(function($entry) {
return $entry['media_url'];
}, $array['data']);
$imageUrls = array_map(function($entry) {
return $entry['permalink'];
}, $array['data']);
<?php foreach($mediaUrls as $mediaUrl) {
echo "<img src='".$mediaUrl."' width='270px'/>";
}
?>
I'm doing a var_dump where I'm pulling in both the media_url's and permalinks - I would just like to combine them and I'm unsure how to do that.
The answer has been completed:
$mediaUrls = array_map(function($entry) {
return [
'media_url' => $entry['media_url'],
'permalink' => $entry['permalink']
];
}, $array['data']);
create an array of arrays and iterate over it:
<?php
$mediaUrls = array_map(function($entry) {
return [
'media_url' => $entry['media_url'],
'permalink' => $entry['permalink']
];
}, $array['data']);
foreach($mediaUrls as $entry) {
echo "<img src='{$entry['media_url']}' width='270px' />";
}

Combine two arrays two one and set keys

I have been struggling with this for quite some time. I have two arrays, which I need to combine.
This is my input:
{
"array_one": {
"mrnreference": [
{
"key_0": "18DK00310020B11A84"
},
{
"key_0": "18DK00310020B11B40"
}
]
},
"array_two": {
"shipperreference": [
{
"key_0": "1861575"
},
{
"key_0": "1861549"
}
]
}
}
Now the structure is, that each item in each array follows each other. So, the result should be something like:
{
"result": [
{
"mrn" : "18DK00310020B11A84",
"shipper" : "1861575"
},
{
"mrn" : "18DK00310020B11B40",
"shipper" : "1861549"
}
]
}
However I simply cannot figure out how to do this.
I have tried to merge the two original arrays:
//Input
$array_one = $request->array_one;
$array_two = $request->array_two;
//Merge the two received arrays
$final = array_merge_recursive($array_one, $array_two);
However, this just removes array_one and array_two, but the array is still split up.
How can I combine above array, so it will have below format:
{
"mrn" : "18DK00310020B11B40",
"shipper" : "1861549"
}
You can do this with some custom code:
$array_one = $request->array_one;
$array_two = $request->array_two;
$final = array_map(function ($value, $key) use ($array_two) {
foreach ($value as $k => $v) {
return [
"mrn" => $v,
"shipper" => array_get($array_two, "shipperreference.$key.$k")
];
}
}, array_get($array_one, 'mrnreference'), array_keys(array_get($array_one, 'mrnreference')));
A very quick solution to this would be just to iterate through a for loop.
for($i = 0; $i < count($array_one); $i++){
$final[$i]["mrn"] = $array_one["mrnreference"][$i]; // Mrn key equals array one value
$final[$i]["shipping"] = $array_two["shipperreference"][$i]; // Shipping key equals array two value
}
However, this has a small caveat that it could lead to an error, if $array_one and $array_two are not the same size.
First of all array_map can be used to get the values and then in simple for loop you can combine them. Notice that the size of mrnreference and shipperreference must be the same otherwise it will pop notice
$json = '
{
"array_one": {
"mrnreference": [
{
"key_0": "18DK00310020B11A84"
},
{
"key_0": "18DK00310020B11B40"
}
]
},
"array_two": {
"shipperreference": [
{
"key_0": "1861575"
},
{
"key_0": "1861549"
}
]
}
}
';
$arr = json_decode($json, true);
$ref = array_map(function($e){return $e['key_0'];}, $arr['array_one']['mrnreference']);
$ship = array_map(function($e){return $e['key_0'];}, $arr['array_two']['shipperreference']);
$output = array();
for ($i = 0, $cnt = count($ref); $i < $cnt ; ++$i) {
$output[] = [
'mrn' => $ref[$i],
'shipper' => $ship[$i],
];
}
echo json_encode(['result' => $output]);

json decode array PHP

I'm trying to decode a json string, i want to get just langlinks value,
my json string is:
{
"batchcomplete": "",
"query": {
"pages": {
"105219": {
"pageid": 105219,
"ns": 0,
"title": "Cancer",
"langlinks": [
{
"lang": "ar",
"*": "\u0633\u0631\u0637\u0627\u0646"
}
]
}
}
}
}
I tried this code:
$results = json_decode($api_response, true);
$list = array();
foreach ($results['query']['pages'] as $k => $v)
{
var_dump($v);
foreach($v as $key => $val)
{
array_push($list, $val);
}
}
return $list;
But it does not accede to the value that I want, when i add
var_dump(array_key_exists('langlinks', $v));
it gives me false :/
I just tested this and this seems to return true
$source = file_get_contents('https://en.wikipedia.org/w/api.php?action=query&titles=Cancer&prop=langlinks&lllang=ar&format=json');
$results = json_decode($source, true);
foreach ($results['query']['pages'] as $k => $v)
{
var_dump(array_key_exists('langlinks', $v));die();
}
If you are still having trouble, maybe you can post more code?
$list = array();
$src = json_decode($api_response, true);
foreach ($src['query']['pages'] as $key => $langData) {
foreach ($langData['langlinks'] as $k => $ld);
// var_dump($ld['*']);
}
return $ld['*'];

Why I can't format my JSON object?

I'm trying to construct a json object containing inner objects.
I'm trying the following code - where $ids is an array containing some IDs:
$result = array();
foreach ($ids as $value) {
$tempArray = getCustomOptions($host, $dbUsername, $dbPassword, $dbName, $_SESSION['companyId'], $value);
array_push($result, $tempArray);
}
print_r(json_encode($result));
The getCustomOptions() also returns an array using the following script:
$dataArray = [];
while ($stmt->fetch()) {
$dataArray[] = array(
'id' => $id,
'description' => $description
);
}
The problem is that when I print_r(json_encode($result)); I'm getting the following result:
[
[
{
"id":21,
"description":"Bshd"
},
{
"id":22,
"description":"Gandhi "
},
{
"id":23,
"description":"aaaa"
},
{
"id":24,
"description":"bbbbb"
}
],
[
{
"id":12,
"description":"121"
},
{
"id":13,
"description":"qwe"
},
{
"id":16,
"description":"wD2"
},
{
"id":17,
"description":"we"
}
],
[
]
]
As you can see it returns some arrays inside of an array, but what I really need is the following structure:
{
"data1":[
{
"id":21,
"description":"Bshd"
},
{
"id":22,
"description":"Gandhi "
},
{
"id":23,
"description":"aaaa"
},
{
"id":24,
"description":"bbbbb"
}
],
"data2":[
{
"id":12,
"description":"121"
},
{
"id":13,
"description":"qwe"
},
{
"id":16,
"description":"wD2"
},
{
"id":17,
"description":"we"
}
]
}
I know that I'm missing something really small and basic here, but for me the JSON manipulation in php is still hard.
Can somebody give me a clue or a push?
you can try following code to generate your array in a proper format.
$result = array();
$i=1;
foreach ($ids as $value) {
$tempArray = getCustomOptions($host, $dbUsername, $dbPassword, $dbName, $_SESSION['companyId'], $value);
$result['data'.$i] = $tempArray;
$i++;
}
Don't use array_push() that just creates a normal array element. Use $array_variable[$key] = ... to assign values to a specific associative array key.

Categories