If you have an array within an array, how can you remove the outer array in this laravel code. Current return array.
return view($this->_viewDefaultFile)
->with('id', $this->_formId)
->with('class', $this->_formClass)
->with('elements', $this->_formElements)
->with('ManageJs', $this->_formManageJs);
Current Results
[
0 {
"id": "id",
"group": 0,
"type": "hidden",
"label": "",
"options": [
],
"value": "1"
},
1 {
"id": "taskstream",
"group": 0,
"type": "text",
"label": "Task Stream",
"options": {
"class": "",
"validation": "required"
},
"value": "System down for maintenance"
}
]
But preferred output
[
id {
"id": "id",
"group": 0,
"type": "hidden",
"label": "",
"options": [
],
"value": "1"
},
taskstream {
"id": "taskstream",
"group": 0,
"type": "text",
"label": "Task Stream",
"options": {
"class": "",
"validation": "required"
},
"value": "System down for maintenance"
}
]
So i want to return the Array with (ID) has the key. Any help please.
Here it is:
$array = []; // your array
$new_array = [];
foreach ($array as $item) {
$new_array[$item->id] = $item;
}
Related
I have 2 Multiple-Arrays and I want to compare them. In the second Array I want then show with colors which value has changed, which key is new and which key is removed.
I have found a lot of different solutions, but no one function for me.
Here are my arrays:
{
"originFormation": {
"stationName": "Bern",
"sections": [{
"name": "B",
"cars": [{
"type": "LOK",
"occupancy": "UNKNOWN",
"attributes": [],
"closed": false,
"previousPassage": false,
"nextPassage": false
}]
}, {
"name": "C",
"cars": [{
"type": "CAR",
"number": "1",
"class": "1",
"occupancy": "UNKNOWN",
"attributes": ["AbteilRollstuhl", "AbteilBusiness"],
"closed": false,
"previousPassage": false,
"nextPassage": true
}, {
"type": "CAR",
"number": "1",
"class": "2",
"occupancy": "UNKNOWN",
"attributes": [],
"closed": false,
"previousPassage": true,
"nextPassage": true
}]
}],
"legendItems": [{
"id": "1",
"text": "1st class coach",
"refersTo": "type"
}, {
"id": "2",
"text": "2st class coach",
"refersTo": "type"
}, {
"id": "Fahrtrichtung",
"text": "Direction of travel",
"refersTo": "code"
}, {
"id": "FA",
"text": "Family Coach with play area",
"refersTo": "type"
}, {
"id": "AbteilRollstuhl",
"text": "Wheelchair space",
"refersTo": "code"
}, {
"id": "AbteilVeloPl",
"text": "Bicycle loading: Without reservation",
"refersTo": "code"
}, {
"id": "LK",
"text": "Locomotive",
"refersTo": "type"
}, {
"id": "WR",
"text": "Restaurant 1st and 2nd class",
"refersTo": "type"
}, {
"id": "AbteilBusiness",
"text": "Business zone in 1st class: Reservation possible",
"refersTo": "code"
},
{
"id": "HFS_WG_NUM",
"text": "Coach",
"refersTo": "code"
}, {
"id": "KD",
"text": "No passage",
"refersTo": "type"
}
],
"info": {
"title": "Changes to the composition of the train",
"formationChanges": []
}
}
}
Array2:
{
"originFormation": {
"stationName": "Bern",
"sections": [
{
"name": "B",
"cars": [
{
"type": "LOK",
"occupancy": "UNKNOWN",
"attributes": [],
"closed": false,
"previousPassage": false,
"nextPassage": false
}
]
},
{
"name": "C",
"cars": [
{
"type": "CAR",
"number": "12",
"class": "1",
"occupancy": "UNKNOWN",
"attributes": [
"AbteilRollstuhl",
"AbteilBusiness"
],
"closed": false,
"previousPassage": false,
"nextPassage": true
},
{
"type": "CAR",
"number": "1",
"class": "2",
"occupancy": "UNKNOWN",
"attributes": [
"AbteilStefan"
],
"closed": false,
"previousPassage": true,
"nextPassage": true
},
{
"type": "CAR",
"number": "2",
"class": "1",
"occupancy": "UNKNOWN",
"attributes": [],
"closed": false,
"previousPassage": true,
"nextPassage": true
}
]
}
],
"legendItems": [
{
"id": "1",
"text": "1st class coach",
"refersTo": "type"
},
{
"id": "2",
"text": "2st class coach",
"refersTo": "type"
},
{
"id": "Fahrtrichtung",
"text": "Direction of travel",
"refersTo": "code"
},
{
"id": "FA",
"text": "Family Coach with play area",
"refersTo": "type"
},
{
"id": "AbteilRollstuhl",
"text": "Wheelchair space",
"refersTo": "code"
},
{
"id": "AbteilVeloPl",
"text": "Bicycle loading: Without reservation",
"refersTo": "code"
},
{
"id": "LK",
"text": "Locomotive",
"refersTo": "type"
},
{
"id": "WR",
"text": "Restaurant 1st and 2nd class",
"refersTo": "type"
},
{
"id": "AbteilBusiness",
"text": "Business zone in 1st class: Reservation possible",
"refersTo": "code"
},
{
"id": "AbteilStefan",
"text": "Ich bin ein neues Abteil",
"refersTo": "code"
},
{
"id": "HFS_WG_NUM",
"text": "Coach",
"refersTo": "code"
},
{
"id": "KD",
"text": "No passage",
"refersTo": "type"
}
],
"info": {
"title": "Changes to the composition of the train",
"formationChanges": [
"All Changed"
]
}
}
}
My fonction to compare:
function array_diff_assoc_recursive($array1, $array2)
{
foreach($array1 as $key => $value)
{
if(is_array($value))
{
if(!isset($array2[$key]))
{
$difference[$key] = $value;
}
elseif(!is_array($array2[$key]))
{
$difference[$key] = "<b>".$value."</b>";
}
else
{
$new_diff = array_diff_assoc_recursive($value, $array2[$key]);
if($new_diff != FALSE)
{
$difference[$key] = $new_diff;
}
}
}
elseif(!isset($array2[$key]) || $array2[$key] != $value)
{
$difference[$key] = "<b>".$value."</b>";
}
}
return !isset($difference) ? 0 : $difference;
}
var_dump(array_diff_assoc_recursive($array2, $array1));
This difference i get:
[originformation][sections][1][cars][0][number] -> newValue 12
[originformation][sections][1][cars][1][attributes] -> newValue AbteilStefan
[originformation][sections][1][cars][2] -> all Attributes are new
[originformation][legendItems][9][id] -> newValue AbteilStefan
[originformation][legendItems][9][text] -> newValue Ich bin ein neues Abteil
[originformation][legendItems][10] -> all Attributes are new
[originformation][legendItems][11] -> all Attributes are new
[originformation][info][formationChanges][0] => newValue All Changed
The difference i expected
[originformation][sections][1][cars][0][number] -> newValue 12
[originformation][sections][1][cars][1] -> all Attributes are new
[originformation][legendItems][9] -> all Attributes are new
[originformation][info][formationChanges][0] => newValue All Changed
Problem
My function doesn't see, that car in Array2 I put in a complete new car and also a complete new legendItem and the rest is still the same.
Does someone know how I can compare the arrays, that he doesn't check the order of the attributes on the same level?
I have a list of (the result of a query in DB) like this:
[
{
"id": "1",
"parent_id": null,
"title": "مدادنوکی",
"url": "/medadnoki"
},
{
"id": "2",
"parent_id": null,
"title": "جامعه",
"url": "/commiunity"
},
{
"id": "5",
"parent_id": "1",
"title": "درباره ی مدادنوکی",
"url": "/about"
},
{
"id": "6",
"parent_id": "1",
"title": "درباره ی مدادنوکی",
"url": "/about"
},
{
"id": "7",
"parent_id": "2",
"title": "همکاران",
"url": "/co-worker"
},
{
"id": "8",
"parent_id": "2",
"title": "اساتید",
"url": "/masters"
}
]
But I want to create an object like this:
[
{
"title": "مدادنوکی",
"url": "/medadnoki",
"subs" : [
{
"title": "درباره مدادنوکی",
"url": "/about"
},
{
"title": "درباره مدادنوکی",
"url": "/about"
},
{
"title": "درباره مدادنوکی",
"url": "/about"
},
{
"title": "درباره مدادنوکی",
"url": "/about"
}
]
},
{
"title": "جامعه",
"url": "/soc",
"subs" : [
{
"title": "همکاران",
"url": "/co-work"
},
{
"title": "اساتید",
"url": "/masters"
}
]
}
]
I have handled this process with two foreach in php and it means I process data twice and it is not efficient and will be slow.
Is there any Idea to doing this with just one foreach?
using one foreach means faster than two foreach twice and It will show the result in big data
Assuming you have the results in an order where the parents appear in the results before any children they may have, this should work:
$nested = [];
foreach($results as $r) {
if($r['parent_id'] === null) {
$nested[$r['id']] = [
'title' => $r['title'],
'url' => $r['url'],
'subs' => []
];
continue;
}
$nested[$r['parent_id']]['subs'][] = [
'title' => $r['title'],
'url' => $r['url']
];
}
$nested = array_values($nested);
I have a JSON Schema for new orders, that consists of order list and address.
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "array",
"properties": {
"order": {
"type": "array",
"items": {
"type": "array",
"properties": {
"product_id": {
"type": "integer"
},
"quantity": {
"type": "integer"
}
},
"required": [
"product_id",
"quantity"
]
}
},
"address": {
"type": "array",
"properties": {
"name": {
"type": "string"
},
"phone": {
"type": "integer"
},
"address1": {
"type": "string"
},
"address2": {
"type": "string"
},
"city": {
"type": "string"
},
"state_or_region": {
"type": "string"
},
"country": {
"type": "string"
}
},
"required": [
"name",
"phone",
"address1",
"city",
"state_or_region",
"country"
]
}
},
"required": [
"order",
"address"
]
}
But it doesn't seem to actually validate the items at all (I'm using Laravel 5.2 with "justinrainbow/json-schema": "~2.0" ):
$refResolver = new \JsonSchema\RefResolver(new \JsonSchema\Uri\UriRetriever(), new \JsonSchema\Uri\UriResolver());
$schema = $refResolver->resolve(storage_path('schemas\orders.post.json'));
$errors = [];
$input = Request::input();
// Validate
$validator = new \JsonSchema\Validator();
$validator->check($input, $schema);
$msg = [];
if ($validator->isValid()) {
return Response::json(['valid'], 200, [], $this->pritify);
} else {
$msg['success'] = false;
$msg['message'] = "JSON does not validate";
foreach ($validator->getErrors() as $error) {
$msg['errors'][] = [
'error' => ($error['property'] = ' ') ? 'wrong_data' : $error['property'],
'message' => $error['message']
];
}
return Response::json($msg, 422, [], $this->pritify);
}
A request like this always comes valid:
{
"order": [
{
"product_id": 100,
"quantity": 1
},
{
"product_id": 0,
"quantity": 2
}
],
"address": []
}
Any ideas what am I doing wrong?
You have messed array and object types. The only array value in your scheme must be order. Fixed scheme:
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"order": {
"type": "array",
"items": {
"type": "object",
"properties": {
"product_id": {
"type": "integer"
},
"quantity": {
"type": "integer"
}
},
"required": [
"product_id",
"quantity"
]
}
},
"address": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"phone": {
"type": "integer"
},
"address1": {
"type": "string"
},
"address2": {
"type": "string"
},
"city": {
"type": "string"
},
"state_or_region": {
"type": "string"
},
"country": {
"type": "string"
}
},
"required": [
"name",
"phone",
"address1",
"city",
"state_or_region",
"country"
]
}
},
"required": [
"order",
"address"
]
}
And validation errors I got with you test data:
JSON does not validate. Violations:
[address.name] The property name is required
[address.phone] The property phone is required
[address.address1] The property address1 is required
[address.city] The property city is required
[address.state_or_region] The property state_or_region is required
[address.country] The property country is required
I've gone through a few examples and documentations and kind find a solution update a nested object in the this result set.
I can add one (if one does not exist)
I can append to it (if one does exist)
Can't figure out how to delete a selected entry.
Is there a method I can use (using the php client) to add an entry if it does not exist / update an entry if it does exist / delete the second entry.
I'm inheriting this problem and am new to Elastic search.
Thanks.
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "products",
"_type": "categories",
"_id": "AUpRjtKZfXI7LIe9OpNx",
"_score": 1,
"_source": {
"name": "Primary",
"description": "Primary Category",
"slug": "Primary",
"created": "2014-12-16 00:25:22",
"parent": [
{
"name": "First One",
"description": "Test",
"id": "ae74ea4e2e865ed3fd60c18a06e69c65",
"slug": "first-one"
},
{
"name": "Second One",
"description": "Testing Again",
"id": "c8dbe5143c8dfd6957fa33e6cea7a0a8",
"slug": "second-one"
}
]
}
}
]
}
}
Do you want to do all three in the same operation?
Deleting the second nested object is achieved through a script which removes the second element:
PUT /products
{
"mappings": {
"categories": {
"properties": {
"parent": {
"type": "nested",
"properties": {
"name": { "type": "string" },
"description": { "type": "string" },
"id": { "type": "string", "index": "not_analyzed" },
"slug": { "type": "string" }
}
}
}
}
}
}
PUT /products/categories/1
{
"name": "Primary",
"description": "Primary Category",
"slug": "Primary",
"created": "2014-12-16 00:25:22",
"parent": [
{
"name": "First One",
"description": "Test",
"id": "ae74ea4e2e865ed3fd60c18a06e69c65",
"slug": "first-one"
},
{
"name": "Second One",
"description": "Testing Again",
"id": "c8dbe5143c8dfd6957fa33e6cea7a0a8",
"slug": "second-one"
}
]
}
POST /products/categories/1/_update
{
"script" : "ctx._source.parent.remove(1)",
"lang": "groovy"
}
GET /products/categories/1
So in PHP code (using the official PHP client), the update would look like:
$params = [
'index' => 'products',
'type' => 'categories',
'id' => 1,
'body' => [
'script' => 'ctx._source.parent.remove(1)',
'lang' => 'groovy'
]
];
$result = $client->update($params);
I'm trying to make a json that looks like this:
{
"data": {
"error_message": "",
"data": {
"person": [
[
{
"name": "teset1",
"image": "http://test.co.il/test/icons/billadress.png"
},
{
"name": "test2",
"image": "http://test.co.il/test/icons/email.png"
},
{
"name": "test3",
"image": "http://test.co.il/test/icons/homeicon.png"
}
],
[
{
"name": "a",
"image": "http://test.co.il/shay/keykit/icons/billadress.png"
},
{
"name": "b",
"image": "http://test.co.il/shay/keykit/icons/email.png"
},
{
"name": "c",
"image": "http://dvns.co.il/shay/keykit/icons/homeicon.png"
}
],
[
{
"name": "a",
"image": "http://test.co.il/test/icons/billadress.png"
},
{
"name": "b",
"image": "http://test.co.il/test/icons/email.png"
},
{
"name": "c",
"image": "http://dvns.co.il/test/icons/homeicon.png"
}
],
]
}
},
}
This is the code i'm using after i'm getting the name & image from the mysql query:
$response = $this->_db->query($query)->result_array();
$icons_results = array();
$obj = new stdclass();
foreach ($response as $key => $response) {
$icons_model = new icons_model();
$icons_model->init($response);
$obj->families[] = $icons_model;
}
return $obj;
SO .. this is what i'm getting:
{
"data": {
"families": [
{
"id": "1",
"name": "a",
"image_url": "http://test.co.il/shay/keykit/icons/billadress.png"
},
{
"id": "2",
"name": "b",
"image_url": "http://test.co.il/shay/keykit/icons/email.png"
},
{
"id": "3",
"name": "c",
"image_url": "http://test.co.il/test/icons/homeicon.png"
},
{
"id": "6",
"name": "f",
"image_url": "http://test.co.il/test/icons/homeicon.png"
},
{
"id": "4",
"name": "d",
"image_url": "http://test.co.il/test/icons/billadress.png"
},
{
"id": "5",
"name": "e",
"image_url": "http://test.co.il/test/icons/billadres2323s.png"
},
and do on.
How to i make that every three object will be in a group? (like the first example)
Try this:
foreach ($response as $key => $response) {
$icons_model = new icons_model();
$icons_model->init($response);
$obj->families[(int)($key / 3)][] = $icons_model;
}