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

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

Related

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

Multidimensional array to text using only keys

I have an array of this sort:
$array = [
"Darren" => [
"age" => "18",
"work" => [
"occupation" => "developer",
"company" => "ABC Ltd"
]
],
"John" => [
"age" => "24",
"work" => [
"occupation" => "developer",
"company" => "ABC Ltd",
"url" => "www.example.com"
],
]
]
And would like to merge the keys with a dot in between, depending on the array's hierachy:
"Darren.age"
"Darren.work.occupation"
"Darren.work.company"
...
The function that I made so far is
public function buildExpressionKey($array, $parentKey = null){
$expression = [];
foreach($array as $key=>$value){
if(is_array($value)){
array_push($expression, $parentKey. implode(".",
$this->buildExpressionKey($value, $key)));
}else{
array_push($expression, $key);
}
}
return $expression;
}
it is returning this value at the moment:
[
[0] => "age.Darrenoccupation.company"
[1] => "age.Johnoccupation.company.url"
]
Was wondering if it is possible to make a function which automatically does merges the keys like that, thanks in advance :)
What you are currently asking for:
<?php
$people =
[
'John' =>
[
'Occupation' => 'Developer',
'Age' => 18
],
'Darren' =>
[
'Occupation' => 'Manager',
'Age' => 40
]
];
foreach($people as $name => $value)
foreach($value as $k => $v)
$strings[] = $name . '.' . $k;
var_export($strings);
Output:
array (
0 => 'John.Occupation',
1 => 'John.Age',
2 => 'Darren.Occupation',
3 => 'Darren.Age',
)
Managed to resolve this issue :)
/**
* #param $array
* #return array
*/
public function buildExpressionKey($array){
$iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($array));
$keys = array();
foreach ($iterator as $key => $value) {
// Build long key name based on parent keys
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$key = $iterator->getSubIterator($i)->key() . '.' . $key;
}
$keys[] = $key;
}
return $keys;
}
Found something similar on here: Get array's key recursively and create underscore separated string

Array data issue Laravel

I have an array issue in here and I'm spending a lot of time with.
I get a list of array like this form
array:4 [
0 => array:20 [▼
"id" => 58
"id_business" =>
"id_branch" =>
"affected_branches" => " " ▶"
"name" => ""
"banner" => ""
"description" => ""
"url" =>
"start_date" => ""
"end_date" => ""
"nr_pages" => 4
"nr_products" => 0
"type" => "global"
"views" => 24
"visible" => "yes"
"delete" => "no"
"user_create_id" =>
"user_modify_id" =>
"created_at" => ""
"updated_at" => "2017-06-07 14:19:23"]
]
by the following code
$data = Offers::whereIn('id_business', $business_id_array)
->where([
'visible' => 'yes',
'delete' => 'no'
])
->where('end_date', '>=', date('Y-m-d h:m:i'))
->orderBy('id', 'desc')->get()
->toArray();
when i try to make a foreach loop for all arrays that came, in this case 4, it does not return me 4 values, but only one.
The loop is:
foreach ($data as $key => $slide)
{
$offers = DB::select('SELECT o.`id`... WHERE o.`id` = ?',[$slide['id']]);
}
return view('...', ['offers' => $offers]);
}
I pass this values in query to get the id of each of arrays
o.`id` = ?',[$slide['id']]
PS: PLS Help Me :)
You're overwriting $offers value with each iteration, so change your code to:
$offers = [];
foreach ($data as $key => $slide) {
$offers[] = DB::select...
}
You need to change $offres in to array
$offers = array();
foreach ($data as $key => $slide)
{
$offers[] = DB::select('SELECT o.`id`... WHERE o.`id` = ?',[$slide['id']]);
}
return view('...', ['offers' => $offers]);

Push element in array in last 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;
}

Multidimensional array search to return master key

$main_array= array(
"Key1" => array(1,2,14,15,16,17,18,19,22,45,47),
"Key2" => array(6,7,40,41,42,43,48,51,52),
"Key3" => array(4,5,8,46,49,53),
"Key4" => array(3,12,13,50),
"Key5" => array(0,9,10,11,20,23,44,),
"Key6" => array(21,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,55,56,57),
"Key7" => array(53)
);
Could you point me how can I get the KeyX value ?
Desired command $getKey(53) - 53 is in the Key7
Try something like this:
foreach ($main_array as $key => $value) {
if(is_array($value) && array_search($search, $value) !== false) {
return $key;
}
}

Categories