Manipulate array foreach - php

I have array 1 and it should be 2
Does anyone have an idea / solution?
Do i need foreach or for loop?
1.
Array
(
[0] => Array
(
[category_id] => 5
[category] => Pages
)
)
Must be:
Array
(
[0] => Array
(
[5] => Pages
)
)
I have this but this doent work...
for($x = 0; $x <= $counter; $x++){
foreach ($Categories[$x] as $key => $value){
echo $key.' '. $value.'<br>';
}
$test[$x]['category_id'] .= $Categories[$x]['category'];
}
Thanks for all the help!

Code:
<?php
$arr = array(
array(
'category_id' => 5 ,
'category' => 'Pages',
),
);
$new = array();
foreach ($arr as $item) {
$new[] = array(
$item['category_id'] => $item['category']
);
}
print_r($new);
Result:
Array
(
[0] => Array
(
[5] => Pages
)
)

$output=array();
foreach($array as $k=>$v)
{
$output[$v['category_id']]=$v['category'];
}
echo "<pre />";
print_r($output);
Demo1
Demo 2
for multidimensinal result :
$output=array();
foreach($array as $k=>$v)
{
$output[][$v['category_id']]=$v['category'];
}
echo "<pre />";
print_r($output);

As you said you will need a foreach loop to manupulate you array.
Example
$array = array
(
'0' => array
(
'category_id' => '5',
'category' => 'Pages'
)
);
$new_array = array();
foreach($array as $val)
{
$new_array[$val['category_id']] = $val['category'];
}
var_dump($new_array);
this will output
array(1) { [5]=> string(5) "Pages" }

Related

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

Get only Numeric values from Array in PHP

I have an array that looks something like this:
Array (
[0] => Array ( [country_percentage] => 5 %North America )
[1] => Array ( [country_percentage] => 0 %Latin America )
)
I want only numeric values from above array. I want my final array like this
Array (
[0] => Array ( [country_percentage] => 5)
[1] => Array ( [country_percentage] => 0)
)
How I achieve this using PHP?? Thanks in advance...
When the number is in first position you can int cast it like so:
$newArray = [];
foreach($array => $value) {
$newArray[] = (int)$value;
}
I guess you can loop the 2 dimensional array and use a preg_replace, i.e.:
for($i=0; $i < count($arrays); $i++){
$arrays[$i]['country_percentage'] = preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
Ideone Demo
Update Based on your comment:
for($i=0; $i < count($arrays); $i++){
if( preg_match( '/North America/', $arrays[$i]['country_percentage'] )){
echo preg_replace( '/[^\d]/', '', $arrays[$i]['country_percentage'] );
}
}
Try this:
$arr = array(array('country_percentage' => '5 %North America'),array("country_percentage"=>"0 %Latin America"));
$result = array();
foreach($arr as $array) {
$int = filter_var($array['country_percentage'], FILTER_SANITIZE_NUMBER_INT);
$result[] = array('country_percentage' => $int);
}
Try this one:-
$arr =[['country_percentage' => '5 %North America'],
['country_percentage' => '0 %Latin America']];
$res = [];
foreach ($arr as $key => $val) {
$res[]['country_percentage'] = (int)$val['country_percentage'];
}
echo '<pre>'; print_r($res);
output:-
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You can use array_walk_recursive to do away with the loop,
passing the first parameter of the callback as a reference to modify the initial array value.
Then just apply either filter_var or intval as already mentioned the other answers.
$array = [
["country_percentage" => "5 %North America"],
["country_percentage" => "0 %Latin America"]
];
array_walk_recursive($array, function(&$value,$key){
$value = filter_var($value,FILTER_SANITIZE_NUMBER_INT);
// or
$value = intval($value);
});
print_r($array);
Will output
Array
(
[0] => Array
(
[country_percentage] => 5
)
[1] => Array
(
[country_percentage] => 0
)
)
You could get all nemeric values by looping through the array. However I don't think this is the most efficient and good looking answer, I'll post it anyways.
// Array to hold just the numbers
$newArray = array();
// Loop through array
foreach ($array as $key => $value) {
// Check if the value is numeric
if (is_numeric($value)) {
$newArray[$key] = $value;
}
}
I missunderstood your question.
$newArray = array();
foreach ($array as $key => $value) {
foreach ($value as $subkey => $subvalue) {
$subvalue = trim(current(explode('%', $subvalue)));
$newArray[$key] = array($subkey => $subvalue);
}
}
If you want all but numeric values :
$array[] = array("country_percentage"=>"5 %North America");
$array[] = array("country_percentage"=>"3 %Latin America");
$newArray = [];
foreach ($array as $arr){
foreach($arr as $key1=>$arr1) {
$newArray[][$key1] = intval($arr1);
}
}
echo "<pre>";
print_R($newArray);
This is kind of a ghetto method to doing it cause I love using not as many pre made functions as possible. But this should work for you :D
$array = array('jack', 2, 5, 'gday!');
$new = array();
foreach ($array as $item) {
// IF Is numeric (each item from the array) will insert into new array called $new.
if (is_numeric($item)) { array_push($new, $item); }
}

Don't want Array ito combine values

I Have an array in PHP that looks like:
Array ( [2099:360] => 6-3.25 [2130:361] => 4-2.5 [2099:362] => 14-8.75 )
Notice there is Two Keys that are 2099 and one that is 2130. I Have a foreach to remove the everything after the colon. the $drop is my array
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
$a[$ex_part[0]] = $drop_a;
}
print_r($a);
but when I print $a it displays only the recent value of the 2099?
Array ( [2099] => 14-8.75 [2130] => 4-2.5 )
Any Successions? How can I get it to display all of the values?
Thank You for Your Help
One solution is to use a multi-dimensional array to store this strategy:
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
if (isset($a[$ex_part[0]])) {
$a[$ex_part[0]][] = $drop_a;
} else {
$a[$ex_part[0]] = array($drop_a);
}
}
Your resulting data-set will however be different:
Array ( [2099] => Array ( [0] => 6-3.25 [1] => 14-8.75) [2130] => Array ( [0] => 4-2.5 ) )
It may be beneficial to you to preserve the second portion after the colon :
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
if (isset($a[$ex_part[0]])) {
$a[$ex_part[0]][$ex_part[1]] = $drop_a;
} else {
$a[$ex_part[0]] = array($ex_part[1] => $drop_a);
}
}
Now your result is a little more meaningful:
Array ( [2099] => Array ( [360] => 6-3.25 [362] => 14-8.75) [2130] => Array ( [361] => 4-2.5 ) )
Finally you can use alternative key-naming strategy if one is already occupied:
$a = array();
foreach ($drop as $part=>$drop_a){
$ex_part = explode(":", $part);
if (isset($a[$ex_part[0]])) {
$a[altName($ex_part[0], $a)] = $drop_a;
} else {
$a[$ex_part[0]] = $drop_a;
}
}
function altName($key, $array) {
$key++; // Or however you want to do an alternative naming strategy
if (isset($array[$key])) {
return altName($key, $array); // This will eventually resolve - but be careful with the recursion
}
return $key;
}
Returns:
Array
(
[2099] => 6-3.25
[2130] => 4-2.5
[2100] => 14-8.75
)
You basically have a key and a sub key for each entry, so just put them in a multidimensional array:
$a = array();
foreach ($drop as $key => $val) {
list($key, $subKey) = explode(':', $key);
$a[$key][$subKey] = $val;
}
Gives you:
Array
(
[2099] => Array
(
[360] => 6-3.25
[362] => 14-8.75
)
[2130] => Array
(
[361] => 4-2.5
)
)
You can traverse multidimensional arrays by nesting loops:
foreach ($a as $key => $subKeys) {
foreach ($subKeys as $subKey => $val) {
echo "$key contains $subKey (value of $val) <br>";
}
}

php separate array label and values

i have arrays like this
Array(
[0] => Array(
[member_name] => hohoho
[member_type] => SUPPLIER
[interest] => Array(
[0] => HOLIDAY
[1] => MOVIES)
),
[1] => Array(
[member_name] => jajaja
[member_validity] => 13/12/2001
[interest] => Array(
[0] => SPORTS
[1] => FOODS)
)
)
how can I put the array keys and items in a separate variable? for example, i want to have something like
$keyholder[0] = member_name,member_type,interest
$keyholder[1] = member_name,member_validity,interest
$itemholder[0] = hohoho,SUPPLIER,{HOLIDAY,MOVIES}
$itemholder[1] = jajaja,13/12/2001,{SPORTS,FOODS}
Try array_keys() and array_values()
http://php.net/manual/en/function.array-keys.php
http://www.php.net/manual/en/function.array-values.php
You can cycle through an array and get the key and values like this:
foreach ($array as $key => $val)
{
echo $key." - ".$val."<br/>";
}
$keyholder=array();
$itemholder=array();
foreach($original_array as $values){
$inner_keys=array();
$inner_values=array();
foreach($values as $key=>$value){
$inner_keys[]=$key;
$inner_values[]=$value;
}
$keyholder[]=$inner_keys;
$itemholder[]=$inner_values;
}
I think this will do it:
$cnt = count($original);
$keys = array();
$items = array();
for($i = 0; $i < $cnt; $i++) {
$keys[] = array_keys($original[$i]);
$items[] = array_values($original[$i]);
}

Categories