Push element in array in last php - php

I want to push this value(blue) in array at last position right now this value is coming outside the array See below output
$data = array();
foreach ($labors as $result) {
$data[] = (array)$result;
array_push($data,"blue");
}
Output
0 => array:9 [▼
"Date" => "2016-09-04"
"Emp" => "ADDISA01"
"Job" => "24-1604"
"Extra" => null
"Cost" => "26-01-10"
"Union" => null
"Cert" => ""
"Shift" => "1"
"EPay" => "1"
]
"blue" => "1"
expected output
0 => array:9 [▼
"Date" => "2016-09-04"
"Emp" => "ADDISA01"
"Job" => "24-1604"
"Extra" => null
"Cost" => "26-01-10"
"Union" => null
"Cert" => ""
"Shift" => "1"
"EPay" => "1"
"blue" => "1"
]

foreach ($labors as $result) {
$item = (array)$result;
$item['blue'] = '1';
$data[] = $item;
}

$data = array();
foreach ($labors as $result) {
$data1 = (array)$result;
$data1['blue'] = 1;
$data[] = $data1;
}

Did you try,
$data = array();
foreach ($labors as $result) {
$temp = (array)$result;
$temp['blue'] = 1;
$data[] = $temp;
}

This may help you:
$data = array();
foreach ($labors as $result) {
$result = (array) $result;
$result['blue'] = 1;
$data[] = $result;
}

Related

remove array from array if key, value not exist

I have an array in an array in an array. How can I search if any of these arrays have a specific key and value? If not remove this array from array.
Example:
array:3 [▼
0 => array:2 [▼
"location" => array:4 [▶]
"promotions" => array:1 [▶]
]
1 => array:2 [▼
"city" => array:4 [▶]
"promotions" => array:2 [▼
0 => array:5 [▶]
1 => array:5 [▼
"distance" => "0.2288511878121104"
"promoid" => 54
"promo" => Promotion {#1259 ▶}
"product" => Products {#1162 ▶}
"productID" => 5
]
]
]
2 => array:2 [▼
"city" => array:4 [▶]
"promotions" => []
]
]
I want to search "productID" with value 5, and I want to remove array in promotions which doesn`t have this value.
SOLVED
foreach ($locations as $key => $location) {
foreach ($location['promotions'] as $item => $promotions) {
if (is_array($promotions)) {
foreach ($promotions as $k => $value) {
if (!is_array($value)) {
if ($k == 'productID' && $value != $id) {
unset($locations[$key]['promotions'][$item]);
}
}
}
}
}
}
You could use a recursive function and unset() the target
<?php
// example code
$a = [
'test' => 'foo',
'bar' => [
'productID' => 5,
'something' => 'else'
],
'bar2' => [
'productID' => 6,
'something2' => 'else'
]
];
function removeItem($array, $search) {
$s = explode(":",$search);
$skey = trim($s[0]);
$sval = trim($s[1]);
foreach ($array as $n => $v) {
if ($n == $skey && $v == $sval) {
unset($array[$n]);
} else {
if (is_array($v)) $v = removeItem($v, $search);
$array[$n] = $v;
}
}
return $array;
}
$a = removeItem($a, 'productID:5');
print_r($a);
example: https://www.tehplayground.com/zJ2bKplP1pDaV8Ss
Nice solve, you can skip the 3er loop, checking if the key is set with isset()
foreach ($arr as $key => $location) {
if (!is_array($location)) { //if child is not an array ignore it
continue;
}
foreach ($location as $item => $promotions) {
if (!is_array($location)) {//if child is not an array ignore it
continue;
}
if (
isset($promotions['productID']) && //3er lvl, Has the key?
$promotions['productID'] == $id //Has the id
) {
continue; //This is a match so, ignore it
} else {
unset($arr[$key][$item]); //This promotion doesn't have it.
}
}
}
And this one checks at all levels, it uses recursive fn
$ans = deepClean($arr, 'productID', 5);
function deepClean($arr, $search_key, $search_value): ?array
{
if (
isset($arr[$search_key]) && //Has the key
$arr[$search_key] == $search_value //Match value
) {
return $arr;
}
//check children
$currentLevel = [];
foreach ($arr as $key => $value) {
if (!is_array($value)) {
continue;
}
$deepArr = deepClean($value, $search_key, $search_value);
if (is_array($deepArr)) { //child has search?
$currentLevel[$key] = $deepArr;
}
}
return $currentLevel === [] ? null : $currentLevel;
}

Transform data with Laravel helpers

I have an array with the following format:
[
{
"stat_month": "01-2019",
"in_sum": 45443,
"out_sum": 42838,
"balance": 2605
},
{...}
]
But I want to transform this array, hopefully in one operation, to this:
[
"labels" => ["01-2019", "02-2019", "03-2019"],
"in_sum" => [45443, 60947, 56734],
"out_sum" => [42838, 42151, 75486],
"balance" => [2605, 18796, -18752]
]
Any ideas how to solve this in one operation with collection helper functions?
Look at mapToGroups in Laravel Collections:
https://laravel.com/docs/5.8/collections#method-maptogroups
or this solution:
$obj1 = new \stdClass;
$obj1->stat_month = "01-2019";
$obj1->in_sum = 45443;
$obj1->out_sum = 42838;
$obj1->balance = 2605;
$obj2 = new \stdClass;
$obj2->stat_month = "02-2019";
$obj2->in_sum = 55443;
$obj2->out_sum = 52838;
$obj2->balance = 3605;
$collection = collect([
$obj1,$obj2
]);
$aResult = [
'labels' => [],
'in_sum' => [],
'out_sum' => [],
'balance' => []
];
$collection->each(function ($item, $key) use (&$aResult) {
$aResult['labels'][] = $item->stat_month;
$aResult['in_sum'][] = $item->in_sum;
$aResult['out_sum'][] = $item->out_sum;
$aResult['balance'][] = $item->balance;
});
Result:
array:4 [▼
"labels" => array:2 [▼
0 => "01-2019"
1 => "02-2019"
]
"in_sum" => array:2 [▼
0 => 45443
1 => 55443
]
"out_sum" => array:2 [▼
0 => 42838
1 => 52838
]
"balance" => array:2 [▼
0 => 2605
1 => 3605
]
]
You can do this is php like this:
<?php
$array = '[
{
"stat_month": "01-2019",
"in_sum": 45443,
"out_sum": 42838,
"balance": 2605
},
{
"stat_month": "01-2019",
"in_sum": 45443,
"out_sum": 42838,
"balance": 2605
},
{
"stat_month": "01-2019",
"in_sum": 45443,
"out_sum": 42838,
"balance": 2605
}
]';
$array = json_decode($array, true);
$arrayResult = [
'stat_month' => array_column($array, 'stat_month'),
'in_sum' => array_column($array, 'in_sum'),
'out_sum' => array_column($array, 'out_sum'),
'balance' => array_column($array, 'balance')
];
echo "<pre>";
print_r($arrayResult);
?>
You can use simplified array_map() and receive desired output:
$i = 0;
$tmp = ['labels'=>[],'in_sum'=>[],'out_sum'=>[],'balance'=>[]];
array_map(function($obj) use (&$tmp, $i){
foreach($tmp as &$val){
$val[] = array_values(((array)$obj))[$i];
$i++;
}
},$ar);
Demo
Or just simple foreach loop:
$tmp = ['labels'=>[],'in_sum'=>[],'out_sum'=>[],'balance'=>[]];
foreach($ar as $obj) {
$i = 0;
foreach($tmp as &$val){
$val[] = array_values(((array)$obj))[$i];
$i++;
}
}
Demo2
You can replace and re-write this code with Laravel map() function. Try to use dynamic loops instead of predefined object's properties.

How to create dynamic combination with php?

I have 3 array like
$arr = [
"color" => [["name"=>"red"]],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]]
]
$combo = array();
foreach ($arr['size'] as $size) {
foreach($arr['color'] as $color){
foreach ($arr['type'] as $type) {
$variant = json_encode(['size' => $size->name, 'color' =>
$color->name, 'type' => $type->name]);
array_push($combo,$variant);
}
}
}
echo $combo;
// result
0 => "{"size":"15 inch","color":"yellow","type":"metal"}"
1 => "{"size":"18 inch","color":"yellow","type":"plastic"}"
It works properly but but there is can be less or more variants. How can I handle this.
For example
$arr = [
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]]
]
Or
$arr = [
"color" => [["name"=>"red"]],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]],
"brand" => [['name' => 'something']],
]
For what i understand, you have to combine the arrays of properties into one array of
object.
I have to leave now, but if you need a explanation leave a comment and i updated the answers
$arr = [
"color" => [["name"=>"red"],['name'=>'yellow']],
"size" => [["name"=>"18 inch"], ["name"=>"15 inch"]],
"type" => [["name"=>"plastic"]],
"brand" => [['name' => 'something']],
];
function runFor($arr ,&$array, $keys,$index,&$positions){
foreach ($arr[$keys[$index]] as $key => $espec){
$positions[$keys[$index]] = $key;
if($index + 1 < count($keys)){
runFor($arr,$array,$keys, $index+1,$positions);
}else{
$item = (object)[];
foreach ($keys as $key){
$item->$key = $arr[$key][$positions[$key]]['name'];
}
array_push($array,$item);
}
unset($positions[$keys[$index]]);
}
}
$array = array();
$keys = array_keys($arr);
$positions = [];
runFor($arr,$array,$keys,0,$positions);
$combo = array();
foreach ($array as $item){
array_push($combo,json_encode($item));
}
var_dump($combo);

How to expand an array based on quantity

I have an array which stores quantity. I want to convert this into individual array as described below
What i have tried
function expandArray($TICKETTYPE_TEMPARRAY, $readQuantity){
for($i=1; $i<=$readQuantity; $i++){
$TICKETTYPE[] = $TICKETTYPE_TEMPARRAY;
}
}
foreach($TICKETTYPE_TEMPARRAY as $key => $value){
$readQuantity = $value["QUANTITY"];
expandArray($TICKETTYPE_TEMPARRAY, $readQuantity);
}
My array
$myarray = array(
"TICKETPRICE" => "6.0000",
"QUANTITY" => "2",
"COUNTRYID" => "15"
)
Expected output:
[{TICKETPRICE:6.000, QUANTITY:2, COUNTRYID=15},
{TICKETPRICE:6.000, QUANTITY:2, COUNTRYID=15}]
I think you want something like this:
$myarray = array(array(
"TICKETPRICE" => "6.0000",
"QUANTITY" => "2",
"COUNTRYID" => "15"
),
array(
"TICKETPRICE" => "4.0000",
"QUANTITY" => "3",
"COUNTRYID" => "9"
));
$output = array();
foreach ($myarray as $array) {
$output[] = array_fill(0, $array['QUANTITY'], $array);
}
echo json_encode($output);
Output:
[[{"TICKETPRICE":"6.0000","QUANTITY":"2","COUNTRYID":"15"},
{"TICKETPRICE":"6.0000","QUANTITY":"2","COUNTRYID":"15"}
],
[{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"},
{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"},
{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"}
]]
Or if you want a completely flat array:
$output = array();
foreach ($myarray as $array) {
$output = array_merge($output, array_fill(0, $array['QUANTITY'], $array));
}
echo json_encode($output);
Output:
[{"TICKETPRICE":"6.0000","QUANTITY":"2","COUNTRYID":"15"},
{"TICKETPRICE":"6.0000","QUANTITY":"2","COUNTRYID":"15"}
{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"},
{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"},
{"TICKETPRICE":"4.0000","QUANTITY":"3","COUNTRYID":"9"}
]
Demo on 3v4l.org
Simply array_fill and json_encode may help you.
<?php
$myarray = array(
"TICKETPRICE" => "6.0000",
"QUANTITY" => "2",
"COUNTRYID" => "15"
);
$myarray = json_encode(array_fill(0, $myarray['QUANTITY'], $myarray));
print '<pre>';
print_r($myarray);
?>

Parse array to change $key and add new $value => $key

I have such array:
array:8 [
"text" => "rt_field"
"title" => "rt_field"
"type_id" => "rt_attr_uint"
"author_id" => "rt_attr_uint"
"created_at" => "rt_attr_timestamp"
"recommended_at" => "rt_attr_timestamp"
"deleted_at" => "rt_attr_timestamp"
"feeds" => "rt_attr_multi"
]
I need to get this:
array:10 [
"text" => "rt_attr_string"
"text_txt" => "rt_field"
"title" => "rt_attr_string"
"title_txt" => "rt_field"
"type_id" => "rt_attr_uint"
"author_id" => "rt_attr_uint"
"created_at" => "rt_attr_timestamp"
"recommended_at" => "rt_attr_timestamp"
"deleted_at" => "rt_attr_timestamp"
"feeds" => "rt_attr_multi"
]
I try parse array ($key => $value). When $value == rt_field: I try rename $key to $key.'_txt', and add such key as default (without _txt) with $value = rt_attr_string.
My code:
foreach ($array_param as $key => $value) {
if ($value == 'rt_field'){
$array_param_second[$key] = 'rt_attr_string';
$array_param[$key] = $key.'_txt';
}
}
$result = array_merge($array_param, $array_param_second);
return $result;
But $key in first array doesn't edit.
What I do wrong?
You are editing the value in either array. If you want to update a key, you need to create a new key.
You can just add the keys to a new array, this way there is no need for merging after the foreach.
$result = [];
foreach ($array_param as $key => $value) {
if ($value == 'rt_field'){
$result[$key] = 'rt_attr_string';
$result[$key . '_txt'] = $value;
} else {
$result[$key] = $value;
}
}
Here is your solution....
Your Array
$array[] = array(
"text" => "rt_field",
"title" => "rt_field",
"type_id" => "rt_attr_uint",
"author_id" => "rt_attr_uint",
"created_at" => "rt_attr_timestamp",
"recommended_at" => "rt_attr_timestamp",
"deleted_at" => "rt_attr_timestamp",
"feeds" => "rt_attr_multi"
);
Solution
$new = array();
$keys = array_keys($array[0]);
foreach($array as $r){
for($i=0;$i<count($keys);$i++){
$key = $keys[$i];
if($r[$key]=='rt_field'){
$new[$key.'_txt'] = $r[$key];
$new[$key] = 'rt_attr_string';
}
else $new[$i][$key] = $r[$key];
}
}
echo "<pre>";print_r($new);

Categories