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' />";
}
Related
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';
};
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]);
Im studying in array, and I was wondering How can I add key to this kind of array?
{
"items":[
{
"count":"1",
"id":123,
"description":"Bag",
"price":11
},
{
"count":1,
"id":1234,
"description":"10% Discount",
"price":-1.1
}
],
"total":9.9,
"discount_total":9.9
}
because I needed convert the array to have a key base on the id inside the array.
{
"items":{
"123":{
"count":"1",
"cart_id":123,
"description":"Bag",
"price":11
},
"1234":{
"count":1,
"cart_id":1234,
"description":"10% Discount",
"price":-1.1
}
},
"total":9.9,
"discount_total":9.9
}
and this is my code
header('Content-Type: application/json');
$cart_array = json_decode('{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Bag"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}');
foreach ($cart_array->items as $item)
{
$construct["cart_id"] = $item->cart_id;
}
I wanted to ask how can I put the id in the array? I cant use $cart_array['id'] = $value, it returns error.
Uncaught Error: Cannot use object of type stdClass as array
I could really use some explanation here
Following code can help you.
<?php
$json = '{
"items":[
{
"count":"1",
"cart_id":123,
"plu":"TP16",
"description":"Small Four Seasons"
},
{
"count":1,
"cart_id":1234,
"plu":"DISCT10",
"description":"10% Discount"
}
],
"total":9.9,
"discount_total":9.9
}';
$data = json_decode($json,TRUE); //json decode
foreach ($data['items'] as $key => $value)
{
$data['items'][$value['cart_id']] = $value;
unset($data['items'][$key]);
}
echo "<pre>";print_r($data);die;
?>
You don't have to loop at all. You can use array_column to make an array associative with one line of code.
$cart_array['items'] = array_column($cart_array['items'], NULL, 'cart_id');
https://3v4l.org/cPD5n
You can use this code in your application to add keys to indexed array.
foreach($obj as $key=>$val){
foreach ($val as $index=>$content){
$data[$content['id']]=$content;
}
}
You can get same output json data as per you want :
$array = json_decode($data,true);
if(isset($array['items']) && count($array['items']) > 0){
foreach($array['items'] as $key => $value){
$value['cart_id'] = $value['id'];
unset($value['id']);
$array['items'][$value['cart_id']] = $value;
unset($array['items'][$key]);
}
}
echo "<pre>";print_r($array);
echo json_encode($array);
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]
]];
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.