PHP list array and get value - php

I have some difficulties with PHP Arrays. I'm trying to foreach some values, order them with array_multisort and foreach them again so I can create some kind of code.
So what I'm doing is, I'm passing json object as:
"options": [
{"key": "Ships From", "value": "Russia"},
{"key": "Color", "value": "Green"},
{"key": "Size", "value": "M"},
{"key": "Material", "value": "Flex"}
],
So this is received from frontend, and I'm foreaching them like so:
public function findAttribute($product_id, $values)
{
$array = array();
foreach ($values as $key => $value) {
$getAttr = $this->attribute($value['key']);
$getAttrValue = $this->attributeValue($getAttr->id, $value['value']);
$code = $getAttr['label'] . '=' . $getAttrValue['value'];
$collection = array_push($array, array($getAttr->default_order, $code));
}
array_multisort($array, SORT_ASC);
}
As you can see I have $getAttr and $getAttrValue, that selects values from database, in order to get default_order (integer) so I can sort them with multisort.
So actually this code works as expected, and when I write (after multisort) like:
foreach($array as $key => $value){
echo $value[1] .'/';
}
I have expected value, but when I call that function it gives me that it returns NULL, if I change echo to return, I have only first array. If I try like
foreach($array as $key => $value){
$code = $value[1] .'/';
}
return $code;
No success as well.
What should I do?

Because in each iteration you assign a new value to $code so you will only get the last $value [1] in the array (after arranged).
If you want to return a string concatenating all values, you could do as this:
$code = '';
foreach($array as $key => $value){
$code .= $value[1] .'/';
}
return $code;

$code = array();
foreach($array as $key => $value){
$code = $value[$key] .'/';
}
return $code;
Implement your code i hope that will work.

Related

Remove encoding characters from http_build_query

I'm trying to get a JSON Array of Objects and turn into a HTTP query.
The JSON is like this:
[
{"name": "Silvia"},
{"age": 24}
]
I need to turn into this:
?name=Silvia&age=24
I'm trying to use `http_query_params(), but its returning the query like this:
?0%5Bname%5D=Silvia&1%5Bage%5D=24
I tried to use urldecode() but not helped...
Here is my full code:
$jsonArray = json_decode($data['filters']);
$query = http_build_query($jsonArray, null, '&');
$url = $endpoint."?".$query;
Instead of building the query string manually let's use http_build_query() as we should. But first, let's flatten the original array;
$jsonString = '[
{"name": "Silvia"},
{"age": 24}
]';
$jsonArray = json_decode($jsonString, true); // true flag converts to array instead of object
$assoc_array = array();
foreach($jsonArray AS $arr){
foreach($arr AS $key => $val) {
$assoc_array[$key] = $val;
}
}
This returns;
Array
(
[name] => Silvia
[age] => 24
)
Now make the query string;
$queryString = http_build_query($assoc_array);
echo urlencode($queryString); // you can actually skip this
which returns;
name%3DSilvia%26age%3D24
As you can see in this example
This is much more "portable" and you can make a function out of the array flattening method demonstrated.
This will be the solution to your problem :)
$items = json_decode('[
{"name": "Silvia"},
{"age": 24}
]');
$count = 1;
$string = '';
foreach($items as $item)
{
foreach($item as $key => $val)
{
$char = ($count == 1) ? "?" : "&";
$string .= $char . urlencode($key) . "=" . urlencode($val);
$count++;
}
}
echo $string;
This will be ?name=Silvia&age=24

Convert array to JSON in proper format

I'm trying to convert my array to JSON.
My JSON is stored in the database and will later be decoded for permission checking.
Example,
How I want it to be stored in the database:
{ "admin": 1,
"create_posts": 1,
"edit_posts": 1,
"delete_posts": 1 }
How it is being stored now:
{"0":"\"admin\": 1",
"1":"\"create_posts\": 1",
"2":"\"edit_posts\": 1",
"3":"\"delete_posts\": 1"}
My code:
$check_list = $_POST['check_list'];
$list = array();
foreach($check_list as $key) {
$key = '"' . $key .= '": 1';
array_push($list, $key);
}
$json = json_encode($list, JSON_FORCE_OBJECT);
How would I make it so that it stores in the database like I want it to be?
I'm quite new to this, so any hints instead of direct answers is also much appreciated!
UPDATE:
JSON decode and validation:
$permis = json_decode($permissions->permissions, true);
echo ($permis['admin'] == true) ? 'allowed' : 'disallowed';
$arr = [ 'a', 'b', 'c' ];
echo json_encode(
array_combine(
$arr,
array_fill(0, count($arr), 1)
),
JSON_PRETTY_PRINT
);
Output:
{
"a": 1,
"b": 1,
"c": 1
}
http://us3.php.net/manual/en/function.array-combine.php
http://us3.php.net/manual/en/function.array-fill.php
I'm assuming the incoming data looks like this.
$incoming_data = "admin=1&create_posts=1&edit_posts=1&delete_posts=1";
$pairs = parse_str($incoming_data);
so we take the incoming pairs and use the $key as the array index so you don't get the extra array element index.
$permissions = array();
foreach($pairs as $key => $value){
$permissions[$key] = $value;
}
then we encode the new array to get the JSON you're looking for.
print json_encode($permissions);
will print out JSON like this:
{
"admin":"1",
"create_posts":"1",
"edit_posts":"1",
"delete_posts":"1"
}
The main thing to change in your code is this.
foreach($check_list as $key) {
$list[$key] = 1;
}

foreach variable equal to another variable

I want to foreach $key equal to $values to return the $called that matches the $key.
foreach($value as $values);
foreach($json['values'] as $key => $called) {
if($key == $values) {
$myreturns[] = $called;
}
}
return json_encode($myreturns, true);
I have a select multiple which value is a number and if not a number on registration it fails (to stop people changing values).
I populate it with the following json
{
"values": {
"1": "Black",
"2": "Blue",
"3": "Brown",
"4": "Grey",
"5": "Green",
"6": "Hazel",
"7": "Violet"
}
}
if somebody chose black and blue, the values will be 1 and 2.
For example I want foreach $key so the json above if that number is equal to "1" to return the $called that is related to the $key.
I know this is wrong but I want something like this
foreach($key == $values) {
$myreturns[] = $called;
}
Close. use array_push to push the results into a new array, then json encode that.
// json decode into associative array
$values = json_decode($json, true);
// init results
$results = array();
foreach($values as $key => $value) {
if($called == $key) {
array_push($results,$value);
}
}
$result = json_encode($result);
return $result;
Also note that if you want to get an item within a json array, it is easier to just reference it within the array:
$array = json_decode($json,true);
$item = $array[$key];

PHP Can't get the right format for array

I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}

Retrieving array keys from JSON input

I have this array:
$json = json_decode('
{"entries":[
{"id": "29","name":"John", "age":"36"},
{"id": "30","name":"Jack", "age":"23"}
]}
');
and I am looking for a PHP "for each" loop that would retrieve the key names under entries, i.e.:
id
name
age
How can I do this?
Try it
foreach($json->entries as $row) {
foreach($row as $key => $val) {
echo $key . ': ' . $val;
echo '<br>';
}
}
In the $key you shall get the key names and in the val you shal get the values
You could do something like this:
foreach($json->entries as $record){
echo $record->id;
echo $record->name;
echo $record->age;
}
If you pass true as the value for the second parameter in the json_decode function, you'll be able to use the decoded value as an array.
I was not satisfied with other answers so I add my own. I believe the most general approach is:
$array = get_object_vars($json->entries[0]);
foreach($array as $key => $value) {
echo $key . "<br>";
}
where I used entries[0] because you assume that all the elements of the entries array have the same keys.
Have a look at the official documentation for key: http://php.net/manual/en/function.key.php
You could try getting the properties of the object using get_object_vars:
$keys = array();
foreach($json->entries as $entry)
$keys += array_keys(get_object_vars($entry));
print_r($keys);
foreach($json->entries[0] AS $key => $name) {
echo $key;
}
$column_name =[];
foreach($data as $i){
foreach($i as $key => $i){
array_push($column_name, $key);
}
break;
}
Alternative answer using arrays rather than objects - passing true to json_decode will return an array.
$json = '{"entries":[{"id": "29","name":"John", "age":"36"},{"id": "30","name":"Jack", "age":"23"}]}';
$data = json_decode($json, true);
$entries = $data['entries'];
foreach ($entries as $entry) {
$id = $entry['id'];
$name = $entry['name'];
$age = $entry['age'];
printf('%s (ID %d) is %d years old'.PHP_EOL, $name, $id, $age);
}
Tested at https://www.tehplayground.com/17zKeQcNUbFwuRjC

Categories