Replace array key with part of value name - php

I have this format of array
[0] => Array
(
[0] => FieldType: Text
[1] => FieldName: Job title
[2] => FieldFlags: 0
[3] => FieldValue: ICT Manager
[4] => FieldJustification: Left
)
How can i make it look like
[0] => Array
(
[FieldType: ] => Text
[FieldName: ] => Job title
[FieldFlags: ] => 0
[FieldValue: ] => ICT Manager
[FieldJustification: ] => Left
)

Try like below:-
<?php
$array = Array
(
0 => Array
(
0 => 'FieldType: Text',
1 => 'FieldName: Job title',
2 => 'FieldFlags: 0',
3 => 'FieldValue: ICT Manager',
4 => 'FieldJustification: Left'
)
);
$new_array = array();
$i = 0;
foreach($array as $val){ // iterate through array
foreach($val as $k=> $v){ //for each index one array is there so iterate that also
$data = explode(':',$v); // explode the value by :
$new_array[$i][$data[0].":"] = $data[1]; // assign first value as key and second value as value to the new array
}
$i++;
}
echo "<pre/>";print_r($new_array); //print new array
?>
Output:- https://eval.in/394135

$result = array();
foreach ($input as $rows) {
$output = array();
foreach ($rows as $subRow) {
$values = explode(':', $subRow);
if (count($values) == 2) {
$output[$values[0] . ':'] = trim($values[1]);
}
}
$result[] = $output;
}

$array = array(
'0' => array(
'0' => 'FieldType: Text',
'1' => 'FieldName: Job title',
'2' => 'FieldFlags: 0',
'3' => 'FieldValue: ICT Manager',
'4' => 'FieldJustification: Left'
)
);
$nArray = array();
foreach($array as $k => $v){
foreach($v as $key => $value){
if(($pos = strpos($value, ':')) !== false){
$nArray[$k][substr($value, 0, $pos + 1)] = trim(substr($value, $pos + 1));
} else {
$nArray[$k][] = $value;
}
}
}
echo '<pre>';
print_r($nArray);

Related

recursive function to remove '<' and '>' from array keys

I'm trying to get an xml file from an associative array having array keys encapsuled into '<' and '>'
I've tried to use a recursive function but it works correctly only on the first level:
Please remember my final goal is to create an xml, so any appropriate suggest is welcome
this is what I've done so far:
$arr =
array('<Lev0_0>' => 0,
'<Lev0_1>' => 1,
'<Lev0_2>' => array (
'<Lev1_0>' => 2,
'<Lev1_1>' => 3
)
);
print_r(RepairKeysMultidimensional($arr));
function RepairKeysMultidimensional(array $array){
$Keys = array();
foreach($array as $Key => $Value){
$NewKey = str_replace(array('<','>'),'',$Key);
$array[$NewKey] = $Value;
unset($array[$Key]);
if(is_array($Value)){
RepairKeysMultidimensional($Value);
}
}
return $array;
}
the output is:
Array (
[Lev0_0] => 0
[Lev0_1] => 1
[Lev0_2] => Array (
[] => 2
[] => 3
)
)
If that's the structure and you never expect < or > as part of the values, you don't need to loop over it just json_encode it, strip out the chars and the json_decode it back into an array.
<?php
$arr = array(
'<Lev0_0>' => 0,
'<Lev0_1>' => 1,
'<Lev0_2>' => array (
'<Lev1_0>' => 2,
'<Lev1_1>' => 3
)
);
$arr = json_decode(str_replace(array('<','>'), '', json_encode($arr)), true);
print_r($arr);
https://3v4l.org/2d7Hq
Result:
Array
(
[Lev0_0] => 0
[Lev0_1] => 1
[Lev0_2] => Array
(
[Lev1_0] => 2
[Lev1_1] => 3
)
)
Try to add affectation in your if statement:
function RepairKeysMultidimensional(array $array){
$Keys = array();
foreach($array as $Key => $Value){
$NewKey = str_replace(array('<','>'),'',$Key);
$array[$NewKey] = $Value;
unset($array[$Key]);
if (is_array($Value)) {
$array[$NewKey] = RepairKeysMultidimensional($Value);
}
}
return $array;
}
you are not affecting the result of the second call to the outer array!
Try this :
<?php
$arr =
array('<Lev0_0>' => 0,
'<Lev0_1>' => 1,
'<Lev0_2>' => array (
'<Lev1_0>' => 2,
'<Lev1_1>' => 3
)
);
echo str_replace(array('<','>'),'','<Lev0>');
echo '<br/><br/>';
print_r(RepairKeysMultidimensional($arr));
function RepairKeysMultidimensional(array $array){
$Keys = array();
foreach($array as $Key => $Value){
$NewKey = str_replace(array('<','>'),'',$Key);
unset($array[$Key]);
if(is_array($Value)){
$array[$NewKey] = RepairKeysMultidimensional($Value);
}else{
$array[$NewKey] = $Value;
}
}
return $array;
}
The output of this is :
Array (
[Lev0_0] => 0
[Lev0_1] => 1
[Lev0_2] => Array (
[Lev1_0] => 2
[Lev1_1] => 3 ) )

How to convert multi-dimensional array into single array using PHP?

After implementing database queries, I am getting the multi-dimensional array below.
Two Dimensional Array
Array
(
[0] => Array
(
[t1] => test1
)
[1] => Array
(
[t2] => test2
)
[2] => Array
(
[t3] => test3
)
[3] => Array
(
[t4] => test4
)
[4] => Array
(
[t5] => test5
)
)
but I want to convert it to a single dimensional array, like the format below:
One Dimensional Array
Array (
t1 => test1
t2 => test2
t3 => test3
t4 => test4
t5 => test5
)
How can I do this?
I think you can use array_reduce() function.
For example:
$multi= array(0 => array('t1' => 'test1'),1 => array('t2' => 'test2'),2 => array('t3' => 'test3'),3 => array('t4' => 'test4'));
$single= array_reduce($multi, 'array_merge', array());
print_r($single); //Outputs the reduced aray
You can use as follows :
$newArray = array();
foreach($arrayData as $key => $value) {
foreach($value as $key2 => $value2) {
$newArray[$key2] = $value2;
}
}
Where $arrayData is your DB data array and $newArray will be the result.
Assuming that source array is array of arrays and it has no the same keys:
<?php
$src = [
['t1'=>'test1'],
['t2'=>'test2'],
['t3'=>'test3'],
['t4'=>'test4'],
['t5'=>'test5'],
];
$result = call_user_func_array('array_merge', $src);
result via var_dump():
array(5) {
["t1"]=>
string(5) "test1"
["t2"]=>
string(5) "test2"
["t3"]=>
string(5) "test3"
["t4"]=>
string(5) "test4"
["t5"]=>
string(5) "test5"
}
You can use array_reduce() to change values of array. In callback get key of item using key() and select first item using reset().
$newArr = array_reduce($oldArr, function($carry, $item){
$carry[key($item)] = reset($item);
return $carry;
});
Check result in demo
Try this function,
function custom_function($input_array)
{
$output_array = array();
for ($i = 0; $i < count($input_array); $i++) {
for ($j = 0; $j < count($input_array[$i]); $j++) {
$output_array[key($input_array[$i])] = $input_array[$i][key($input_array[$i])];
}
}
return $output_array;
}
$arr = custom_function($arr);
print_r($arr);
Give it a try, it will work.
You can use this
<?php
$temp = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));
$result_array = array();
foreach ($temp as $val) {
foreach ($val as $key => $inner_val) {
$result_array[$key] = $inner_val;
}
}
print_r($result_array);
?>
// Multidimensional array
$arrdata = Array(
'0' => Array(
't1' => 'test1'
) ,
'1' => Array(
't2' => 'test2'
) ,
'2' => Array(
't3' => 'test3'
)
);
// Convert to a single array
$data = array();
foreach($arrdata as $key => $value) {
foreach($value as $key1 => $value1) {
$data[$key1] = $value1;
}
}
echo $data;
Try array map function.
$singleDimensionArray = array_map('current',$multiDimensionArray);
You can use this if you don't care about keeping the correct array keys
function flattenA(array $array) {
$return = array();
array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
return $return;
}
print_r(flattenA($arr));
// Output
Array
(
[0] => test1
[1] => test2
[2] => test3
[3] => test4
[4] => test5
)
Otherwise
function flattenB(array $array) {
$return = array();
array_walk_recursive($array, function($v,$k) use (&$return) { $return[$k] = $v; });
return $return;
}
print_r(flattenB($arr));
// Output
Array
(
[t1] => test1
[t2] => test2
[t3] => test3
[t4] => test4
[t5] => test5
)
Check both on Sandbox
From answer on similar question
For your specific case, I would use array_reduce where I set the initial value with an empty array
array_reduce($arr, function($last, $row) {
return $last + $row;
}, array());
AFTER PHP 7.4
array_reduce($arr, fn ($last, $row) => $last + $row, []);
Result :
[
't1' => 'test1',
't2' => 'test2',
't3' => 'test3',
't4' => 'test4',
't5' => 'test5'
]
Hey #Karan Adhikari Simple like below one:
<?php
$arr1 = array(array("t1" => "test1"), array("t2" => "test2"), array("t3" => "test3"), array("t4" => "test4"), array("t5" => "test5"));
echo "<pre>";
print_r($arr1);//before
$arr2 = array();
foreach($arr1 as $val){
$arr2 = array_merge($arr2, $val);
}
echo "<pre>";
print_r($arr2); // after you get your answer
Please try this function:
function array_merging($multi_array) {
if (is_array($multi_array)) {
$new_arr = array();
foreach ($multi_array as $key => $value) {
if (is_array($value)) {
$new_arr = array_merge($new_arr, array_merging($value));
}
else {
$new_arr[$key] = $value;
}
}
return $new_arr;
}
else {
return false;
}
}
Use this function:
$your_multi_arr = array(array(array('t1'=>'test1'),array('t2'=>'test2'),array('t3'=>'test3'),array('t4'=>'test4')));
$arr1 = array_merging($your_multi_arr);
echo "<pre>";
print_r($arr1);
Hope, this may be useful for you.
You can try traversing the array using PHP while list and each. I took sample code from PHP website the second example you can check it here
$arr = [['t1' => 'test1'],['t2' => 'test2'],['t3' => 'test3'],['t4' => 'test4'],['t5' => 'test5']];
$output = [];
while (list($key, $val) = each($arr)) {
while (list($k, $v) = each($val)) {
$output[$k] = $v;
}
}
print_r($output);
Output created is
Array
(
[t1] => test1
[t2] => test2
[t3] => test3
[t4] => test4
[t5] => test5
)
You can test it on your own in this Sandbox example.
This will do the trick
$array = array_column($array, 't1');
Note: This function array_column introduced in PHP 5.5 so it won't work in earlier versions.
traverse the array and save the key value, Live Demo here.
<?php
$array = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));
$result = [];
array_walk($array, function($value) use(&$result){
foreach($value as $k => $v)
{
$result[$k] = $v;
}
});
var_dump($result);
`$result = "Query"; $key_value = array();`
foreach ($result as $key => $value) {
$key_value[$key['']] = $value[''];
}
//for checking //echo "<pre>" ; print_r($key_value) ; exit;
return $key_value;
pls fill $key['name given in sql query for field'] and $value['name given in sql query for field'] (both are same)
this works for me
$result = [];
foreach($excelEmails as $arr)
{
foreach ($arr as $item){
$result = array_merge($result , $item);
}
}
dd($result);
i would recomment my way to convert all double-dimensional array to single-dimensional array.
<?php
$single_Array = array();
//example array
$array = array(
array('t1' => 'test1'),
array('t2' => 'test2'),
array('t3' => 'test3'),
array('t4' => 'test4'),
array('t5' => 'test5'));
$size = sizeof($array);
//loop to fill the new single-dimensional array
for($count = 0; $count<sizeof($array);$count++)
{
//take the key of multi-dim array
$second_cell = key($array[$count]);
//set the value into the new array
$single_array[$count] = $array[$count][$second_cell];
}
//see the results
var_dump($single_array);
?>
with this script we can take keys and values to create new single-dimensional array.I hope that i was helpfull to you.
you can see the example here: Array Convert Demo

how to extract this array through foreach loop

I have a multidimensional array.I want to extract this array through foreach loop and want to display in a unordered list. how to solve this. please help me. i am trying for 2 days but could not get any solution. i think i'm weak in loop.
Array
(
[id] => 1
[name] => Funny
[category_details] => Array
(
[get_everything] => Array
(
[0] => Array
(
[ci_cat_id] => 1
[img_name] => fapore kapor nosto
)
)
)
)
Array
(
[id] => 4
[name] => Events
[category_details] => Array
(
[get_everything] => Array
(
[0] => Array
(
[ci_cat_id] => 4
[img_name] => elo khushir eid
)
[1] => Array
(
[ci_cat_id] => 4
[img_name] => Eid e bari jacchi
)
)
)
)
i want the output like this
category name1:
1. test1
2. test2
3. test3
category name2:
1. test4
2. test5
3. test6
You need to use the array_column(). First of all you need to loop the array and get the category names, and also you need to get the img_name, for this you have to use the array_column and that function gives you the array of that img_name, so now again loop this new array and print the img_name.
Your array:
$arr = array(
array(
"id" => 1,
"name" => "Funny",
"category_details" => array(
"get_everything" => array(
array(
"ci_cat_id" => 1,
"img_name" => "fapore kapor nosto"
)
)
)
),
array(
"id" => 4,
"name" => "Events",
"category_details" => array(
"get_everything" => array(
array(
"ci_cat_id" => 4,
"img_name" => "elo khushir eid"
),
array(
"ci_cat_id" => 4,
"img_name" => "Eid e bari jacchi"
)
)
)
)
);
procedure:
foreach($arr as $val){
echo $val['name']."<br/>";
$i = 1;
$img_name = array_column($val['category_details']['get_everything'], 'img_name');
foreach($img_name as $v){
echo $i++.' - '.$v."<br/>";;
}
}
Output:
Funny
1 - fapore kapor nosto
Events
1 - elo khushir eid
2 - Eid e bari jacchi
Try this will may help you,
1) If you want array:
foreach ($array as $k=>$v){
foreach ($v['category_details']['get_everything'] as $key => $val){
$finalArray[$v['name']][] = $val['img_name'];
}
}
Output will look like this,
Array
(
[Funny] => Array
(
[0] => fapore kapor nosto
)
[Events] => Array
(
[0] => elo khushir eid
[1] => Eid e bari jacchi
)
)
2)If You want string :
foreach ($array as $k=>$v){
echo $v['name'].'<br/>';
$i=1;
foreach ($v['category_details']['get_everything'] as $key => $val){
echo $i.'. '.$val['img_name'].'<br/>';
$i++;
}
}
Output Will be,
Funny
1. fapore kapor nosto
Events
1. elo khushir eid
2. Eid e bari jacchi
try this one
foreach($array as $value) {
echo $value['name'];
foreach($value['category_details'] as $val) {
$i=1;
foreach($val as $v) {
echo $i++ . '. ' . $v['img_name'];
}
}
}
hope this help..
My Controller
function indexx() {
$emp['get_all_img'] = $this->model_bundle->get_all_img();
$t = $this->model_bundle->get_category();
$i = 1;
foreach ($t as $key => $data) {
//$emp['get_everything'][$key]['id'] = $data['id'];
$emp['get_everything'][$key]['name'] = $data['name'];
$emp['get_everything'][$key]['category_details'] = $this->get_category_wise_image($data['id']);
$i++;
}
$this->layout->view('bundle/add_bundle', $emp);
}
function get_category_wise_image($cat_id) {
$data = $this->model_bundle->get_category_wise_image($cat_id);
$i = 1;
foreach ($data as $key => $data) {
$emp['get_everything'][$key]['ci_cat_id'] = $data['ci_cat_id'];
$emp['get_everything'][$key]['bangla_caption'] = $data['bangla_caption'];
$emp['get_everything'][$key]['images_id'] = $data['images_id'];
$emp['get_everything'][$key]['thumnail'] = $data['thumnail'];
$i++;
}
//echo "<pre>";
//print_r($emp);
return $emp;
}
My Model
function get_all_img()
{
$this->db->select('id, bangla_caption, thumnail');
$query = $this->db->get('images');
return $query->result();
}
function get_category(){
$this->db->select('id, name');
$this->db->from('category');
$this->db->order_by('id');
$result = $this->db->get();
return $result->result_array();
}
function get_category_wise_image($id){
$this->db->select('category_images.id as id, img_id, category_images.cat_id as ci_cat_id, images.cat_id as im_cat_id, bangla_caption, name, thumnail, images.id as images_id');
$this->db->from('category_images');
$this->db->join('category','category.id = category_images.cat_id','left');
$this->db->join('images','images.id = category_images.img_id','left');
$this->db->where('category_images.cat_id',$id);
$result = $this->db->get();
return $result->result_array();
}
view(add_bundle.php)
foreach($get_everything as $tasks){
//echo "<pre>";
//print_r($tasks);
echo '<div class="cat_name">'. $tasks['name'].'</div>';
echo "<ul>";
foreach($tasks as $task){
foreach($task as $p){
foreach($p as $pr){
echo '<div height="50px">
<label><input type="checkbox" name="img_id[]" class="second" value="'.$pr['images_id'].'">';
echo '<img src="'.base_url()."uploads/".$pr['thumnail'].'" width="60px">"'.$pr['bangla_caption'].'"</label></div>';
}
}
}echo "</ul>";
}

Determine whether array key value is blank

I have an array like below, as you can see the last array [adad] value is blank, how can I write an if statement to tell whether this is blank.
Array
(
[K] => Array
(
[0] => mabel__chan
[1] => mabel chan
)
[B] => Array
(
[0] => kieron br
)
[C] => Array
(
[0] => a br
[1] => a
)
[adad] => Array
(
[0] =>
)
)
I have tried doing this
if (count(array_filter($array)) == 0) {}
Pseudo code
if(array[key] == blank) {
echo "is blank";
} else {
echo "isn't blank";
}
**PHP Script this is how I get my data from mongoDB*
The answer below is working correctly when I use echos but now when I'm trying to push into new arrays its broken somewhere I get no data back anymore.
$col = "A" . $user->agencyID;
$db = $m->rules;
$collection = $db->$col;
$id = $_POST['ruleID'];
$search = array(
'_id' => new MongoId($id)
);
$cursor = $collection->find($search);
$validTagsArray = array();
$validArray = array();
foreach ($cursor as $key => $value) {
$temp = array_walk($array, function($v, $k) {
if (count(array_filter($v)) === 0) {
foreach ($value['AutoFix'] as $keyTwo => $valTwo) {
$x = 0;
$validTagsArray['data'][] = array($keyTwo, $x);
}
} else {
foreach ($value['AutoFix'] as $keyTwo => $valTwo) {
$x = 0;
foreach ($valTwo as $key => $value) {
$x++;
}
$validTagsArray['data'][] = array($keyTwo, $x);
}
}
});
}
echo json_encode($validTagsArray);
You can try this -
$array = array
(
'K' => array('0' => 'mabel__chan','1' => 'mabel chan'),
'B' => array('0' => 'kieron br'),
'C' => array('0' => 'a br', '1' => 'a'),
'adad' => array('0' => '')
);
$temp = array_walk($array, function($v, $k) {
if(count(array_filter($v)) === 0) { // check the count of non-empty elements in the sub array
echo $k . ' is empty';
}
});
Output
adad is empty
You can write as:
if([adad][0]== " ")
{
}
You can also try this :
foreach($array as $key=>$value){
if(empty($value))
echo "empty";
}

Deleting redundant data inside an array

I have a problem, I have this result below and I want to remove the same timestamp.
Sample Result:
Array
(
[0] => [1341100800000, 0]
[1] => [1341100800000,85]
[2] => [1343779200000,54]
[3] => [1343779200000, 0]
)
Expecting Output
Array
(
[0] => [1341100800000,85]
[1] => [1343779200000,54]
)
I'm thinking of using explode then substr function to get the value. Here is what I came up so far..
$explode = array();
foreach($string_format as $key => $value) {
$explode[] = explode(',', substr($value, 1));
if((isset($explode[0]) && $explode[0][0] == $explode[1][0])) {
unset($explode[0]);
}
//print_r($explode);
}
wouldn't this be a good use of http://us2.php.net/manual/en/function.array-unique.php
Script:
foreach($string_format as $key => $value) {
$explode = explode(',', $value);
$unique[$explode[0]] = $value;
}
Input:
$string_format = array('0' => '1341100800000, 0',
'1' => '1341100800000,85',
'2' => '1343779200000,54',
'3' => '1343779200000, 0');
Output:
$unique =
Array
(
[1341100800000] => 1341100800000,85
[1343779200000] => 1343779200000, 0
)
This should work fine :)
$explode = array();
$timestmp = array();
foreach($string_format as $key => $value) {
$explode[$key] = explode(',', substr($value, 1));
if( in_array( $explode[$key][0], $timestmp)) {
unset ($explode[$key]);
} else {
$timestmp[]= $explode[$key][0];
}
}

Categories