How to parse array from MySQL column in PHP - php

I have column extra_fields in table.
In column i have array, and I need to parse it
[{"id":"1","value":"fdsds"},{"id":"2","value":"\/images\/powered_by.png"},{"id":"3","value":"fdsfdsfdsfds"},{"id":"4","value":"<p>fdsfdsfdsfds<\/p>"}]
Try to do it with this code,
$extrafields = array();
foreach($this->item->extra_fields as $item)
{
$extrafields[$item->id] = $item->value;
}
but return empty string or...I don't know what

it is unclear as to what you want to achieve but here you go:
$test = json_decode('[{"id":"1","value":"fdsds"},{"id":"2","value":"\/images\/powered_by.png"},{"id":"3","value":"fdsfdsfdsfds"},{"id":"4","value":"<p>fdsfdsfdsfds<\/p>"}]');
$extrafields = array();
foreach ($test as $key => $item) {
$extrafields[$item->id] = $item->value;
}

Related

“How can to fix the problem ‘ number_format error

I would like to shorten the result. I have used nummber_format but always an error appears.Can someone help me.
$arr = array();
foreach ($order->orderPositions as $tax) {
$arr[] = $tax->tax;
}
$unique_data = array_unique($arr);
foreach ($unique_data as $val) {
$totalTaxes[$val] = $order->orderPositions->where('tax',
$val)->sum('TotalPriceWithTax');
}
/*help is needed here*/ number_format((float)$unique_data,2);
Loop the array and save them as the new format either in a new array or the same
$unique_data = array_unique($arr);
foreach ($unique_data as &$val) { //notice the & if you want to change the data points in the unique array
$totalTaxes[$val] = $order->orderPositions->where('tax', $val)->sum('TotalPriceWithTax');
$val = number_format($val,2); // replaces the data in unique array
$new[] = number_format($val,2); // add to new array if you need unique array
}

How do I get the commun results in a for loop in a unknown array length PHP

I have a array of dates, I would like to get all values that are in all of them, thats my example:
$array = [
{"d1":["2016-01-04","2016-01-11","2016-01-18","2016-01-25","2016-02-01"]},
{"d2":["2016-01-05","2016-01-11","2016-01-19","2016-01-25","2015-12-12"]},
{"d3":["2016-01-05","2016-01-11","2016-01-25"]},
{"d4":["2016-01-04","2016-01-11","2016-01-25"]}
]
As result:
$result = ["2016-01-11", ,"2016-01-25"];
Here is a working example (can be optimized, but it should work):
$array = json_decode('[
{"d1":["2016-01-04","2016-01-11","2016-01-18","2016-01-25","2016-02-01"]},
{"d2":["2016-01-05","2016-01-11","2016-01-19","2016-01-25","2015-12-12"]},
{"d3":["2016-01-05","2016-01-11","2016-01-25"]},
{"d4":["2016-01-04","2016-01-11","2016-01-25"]}
]');
$allArrays = array();
foreach ($array as $object) {
foreach ($object as $datesArray) {
array_push($allArrays, $datesArray);
}
}
$sharedDates = call_user_func_array('array_intersect',$allArrays);
var_dump($sharedDates);

Remove from array if id exists in database?

I am pulling data from an api and as such i have a loop that stores some ids into an array.
What i need to do is select all ids from my database and then remove any ids that have been found in the database from the initial array. so i can continue to query the api for ids that i do not have currently.
To make more sense please look below:
$matches = $database->get_results('SELECT match_id FROM `matches` WHERE `order_id`='.$order_id);
if ($matchlist->totalGames !== 0) {
foreach ($matchlist as $key) {
$gameIds[] = $key->matchId;
}
}
I need to remove the ids from $gameIds if they already are stored in the $matches.
Any ideas?
Thanks
I have tried:
$matches = $database->get_results('SELECT `match_id` FROM `matches` WHERE `order_id`='.$order_id);
if ($matchlist->totalGames !== 0) {
foreach ($matchlist as $key) {
$gameIds[] = $key->matchId;
}
$arr_matches = object2array($matches);
$new_array = array_diff($arr_matches, $gameIds);
var_dump($new_array);
}
error:
Catchable fatal error: Object of class stdClass could not be converted to string
Step 1: Change object to array
function object2array($object)
{
if (is_object($object)):
foreach ($object as $key => $value):
$array[$key] = $value;
endforeach;
else:
$array = $object;
endif;
return $array;
}
Step 2:
$arr_matches = object2array($matches)
$new_array = array_diff($arr_matches , $gameIds);
// Will remove all elements contained in $gameIds from $arr_matches array.

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;
}

Sorting data from two different sources (PHP)

I need to combine two different data types, an array and an array object.
I then need to display them on a page in order of a certain attribute (date).
The markup for access is similar to the following:
foreach($array as $item){
$item['date'];
}
and
foreach($object as $item){
$item->post->date
}
is array_merge what I need, or something different?
Not that if possible I'd like to do this on the fly, as data will be changing rapidly and there is no need for storage.
Thanks!
Here's how I would do it:
// array we will use for sorting
$finalArray = array();
// add the array's using the date as the key
foreach($array as $item){
$key = $item['date']; // use date here, example $key = date('l \t\h\e jS',$item['date']);
$finalArray[$key] = $item;
}
// add the objects's using the date as the key
foreach($object as $item){
$finalArray[$item->post->date] = $item;
}
//now sort by keys as Xeoncross noted
ksort($finalArray);
foreach($finalArray as $date=>$objOrArray){
if(is_array($objOrArray)){
//do your array printing here
} else {
//do your object printing here
}
}
Ofcourse we can turn the object into an array with get_object_vars, and use whatever sorting function on the final array, the important part is that we want to sort by date and that's why we need it to be our key.
Hope that helped.
foreach($array as $item){
$array_new[] = $item['date'];
}
foreach($object as $item){
$array_new[] = $item->post->date;
}
sort($array_new);
$dates = array();
foreach ($array as $item) {
  $dates[] = $item['date'];
}
foreach ($object as $item) {
$dates[] = $item->post->date;
}
sort($dates);
foreach ($dates as $date) {
echo $date;
}
You could try this if you need multiple values from the objects (not just date) and you don't mind duplicates being erased.
// $array is already defined right?
$object = json_decode(json_encode($object), TRUE);
$data = array_merge($array, $object);
print_r($data); // now test it
http://us2.php.net/array_merge
http://us3.php.net/json_decode (note the second TRUE param)
Edit
Based on Perfection's answer, (and re-reading the question) I would do this:
$finalArray = array();
foreach($array as $item)
{
$finalArray[$item['date']] = $item;
}
foreach($object as $item)
{
$finalArray[$item->post->date] = json_decode(json_encode($item), TRUE);
}
ksort($finalArray);
foreach($finalArray as $date => $item)
{
// Everything is an array now
}

Categories