PHP : Replacing keys with incremental integer - php

I have this stdClass Object
Array (
[0] => stdClass Object ( [criteria1] => 1 [criteria2] => 2 [criteria3] => 2 )
[1] => stdClass Object ( [criteria1] => 2 [criteria2] => 1 [criteria3] => 1 )
[2] => stdClass Object ( [criteria1] => 1 [criteria2] => 1 [criteria3] => 1 )
)
I want to replace the keys into an integer like below
Array (
[0] => stdClass Object ( [0] => 1 [1] => 2 [2] => 2 )
[1] => stdClass Object ( [0] => 2 [1] => 1 [2] => 1 )
[2] => stdClass Object ( [0] => 1 [1] => 1 [2] => 1 )
)
Then I add this function, $arr is for the array of object, $len is for the number of columns of the array
function replace_key($arr,$len) {
$temp_array = array();
foreach ($arr as $key => $val) {
$object = new stdClass();
$x = (array) $val;
foreach ($x as $key2 => $value) {
for ($i=0; $i < $len; $i++) {
$new_key = $i;
$object->$new_key = $value;
}
}
$temp_array[] = $object;
}
return $temp_array;
}
But it resulted this output (the keys are already like how I want but the values are all wrong)
Array (
[0] => stdClass Object ( [0] => 2 [1] => 2 [2] => 2 )
[1] => stdClass Object ( [0] => 1 [1] => 1 [2] => 1 )
[2] => stdClass Object ( [0] => 1 [1] => 1 [2] => 1 )
)
I have no idea what part I did it wrong, I already tried to fix it for several hours but nothing seemed to workout and that function code is far the best I could do. Please help me, I'm so stucked.

Try this code
<?php
$a = (object)array("criteria1"=>1,"criteria2"=>2,"criteria3"=>2);
$b = (object)array("criteria1"=>2,"criteria2"=>1,"criteria3"=>1);
$c = (object)array("criteria1"=>1,"criteria2"=>1,"criteria3"=>1);
$test = array($a, $b,$c);
function replace_key($arr) {
foreach ($arr as $key => $val) {
$object =array();
$object =array_values((array)$val);
$temp_array[] = (object)$object;
}
return $temp_array;
}
print_r(replace_key($test));
?>
working code

function replace_key($arr, $len = null)
{
$results = [];
foreach ($arr as $ar) {
$array = array_values((array)$ar);
$results[] = (object)array_slice($array, 0, $len);
}
return $results;
}

Related

Find Unique Value from a array

I have a Multidimensional array, I need to find if array have same value of 'brand' attribute then return its id.
I tried via some array functions but it didn't work.
What I Tried:
1)
$backwards = array_reverse($attribute);
echo '<pre>';
$last_item = NULL;
$i = 0;
foreach ($backwards as $current_item) {
if ($last_item === $current_item[$i]['value']) {
echo '<pre>'; print_r($current_item[$i]['value']);
}
$last_item = $current_item[$i]['value'];
echo '<pre>'; print_r($last_item);
$i++;
}
2)
$j = 1;
$i = 0;
foreach ($attributeValues as $attributeData) {
foreach ($attribute as $value) {
if($value[$i]['value'] == $value[$j]['value']) {
echo '<pre>'; print_r($value); die();
}
$j++;
}
}
All my solution's not worked, please help.
[0] => Array
(
[0] => Array
(
[name] => brand
[value] => 54
[id] => 5251
[price] => 15000.0000
)
[1] => Array
(
[name] => model
[value] => 1200
[id] => 5251
[price] => 15000.0000
)
)
[1] => Array
(
[0] => Array
(
[name] => brand
[value] => 54
[id] => 5250
[price] => 15000.0000
)
[1] => Array
(
[name] => model
[value] => 1200
[id] => 5250
[price] => 12000.0000
)
)
[2] => Array
(
[0] => Array
(
[name] => brand
[value] => 89
[id] => 518
[price] => 100.0000
)
[1] => Array
(
[name] => model
[value] => 12
[id] => 518
[price] => 100
)
)
If [name]=>brand and [name]=>model value's of first array is same as second array's value then return [id].
You need two for loop.
$result =[];
foreach ($arr as $key => $value) {
foreach($value as $v){
$result[$v['name']][] = $v['id'];
}
}
$result = array_map("array_unique", $result); // to make it unique
print_r($result);
// if you want to check ids for brand
//print_r($result['brand']);
Output:
Array
(
[brand] => Array
(
[0] => 5251
[1] => 5250
[3] => 518
)
[model] => Array
(
[0] => 5251
[1] => 518
)
)
Demo.
EDIT
Then you can group it by name and value of it
$result =[];
foreach ($arr as $key => $value) {
foreach($value as $v){
$result[$v['name']."|".$v['value']][] = $v['id'];
}
}
$result = array_map("array_unique", $result);
print_r($result);die;
Demo.
you can use foreach and iterate through the array
$res = [];
foreach($arr as $k => $v){
if($v[0]['name'] == $v[1]['name'])
$res[$v[0]['name']] = $v[0]['id'];
}
If you want to match the index value try this
foreach($arr as $k => $v){
if($v[0]['value'] == $v[1]['value'])
$res[] = $v[0]['id'];
}
Working example

php | Bug with recursion

I have a problem with my recursional function. May be you can help me.
My function below:
function showTree($items, $level = 0) {
$arr = [];
foreach ($items as $item) {
$arr[] = str_repeat(":", $level * 2) . $item['name'] . "<br />";
if (!empty($item['children'][0])) {
$level++;
$arr[] = $this->showTree($item['children'], $level);
}
}
return $arr;
}
And this generate the output:
Array
(
[0] => Category1
[1] => Array
(
[0] => ::SubCategory2
[1] => ::SubCategory1
[2] => Array
(
[0] => ::::SubSubCategory
)
)
)
But I need a little bit other data as my output:
Array
(
[0] => Category1
[1] => ::SubCategory2
[2] => ::SubCategory1
[3] => ::::SubSubCategory
)
Where is my mistake? Thanks!
P>S:
Input:
Array
(
[0] => Array
(
[id] => 1
[name] => Category1
[parent] => 0
[children] => Array
(
[0] => Array
(
[id] => 4
[name] => SubCategory2
[parent] => 1
[children] => Array
(
)
)
[1] => Array
(
[id] => 2
[name] => SubCategory1
[parent] => 1
[children] => Array
(
[0] => Array
(
[id] => 3
[name] => SubSubCategory
[parent] => 2
[children] => Array
(
)
)
)
)
)
)
)
Change this line:
$arr[] = $this->showTree($item['children'], $level);
to:
$arr = array_merge($arr, $this->showTree($item['children'], $level));
I.e. don't add the array returned while walking the children as a new value into the current array but append the values from it to the current array.
Try this:
function showTree($items, $level = 0, &$arr = array()) {
foreach ($items as $item) {
$arr[] = str_repeat(":", $level * 2) . $item['name'] . "<br />";
if (!empty($item['children'][0])) {
$level++;
$this->showTree($item['children'], $level, $arr);
}
}
return $arr;
}

Group and merge array row data based on one column

I have an array a bit like:
Array (
[1] => Array
(
[1] => 21
[2] => 3
[0] => Analyst
)
[2] => Array
(
[1] => 47
[2] => 8
[0] => Catalysis
)
[3] => Array
(
[1] => 1
[2] => 0
[0] => Biomaterials
)
[4] => Array
(
[3] => 12
[4] => 2
[0] => Analyst
)
[5] => Array
(
[5] => 12
[6] => 2
[0] => Analyst
)
...
However I would like to renumber those entries with the same [0] value so that I end up with
[1] => Array
(
[1] => 21
[2] => 3
[3] => 12
[4] => 2
[5] => 12
[6] => 2
[0] => Analyst
)
So far I've tried getting the [0] values out of the $results array by putting them in their own array and saying if you're already there then add [3] and [4] to where [1] and [2] are in a new array but it's not working.
$final = array();
$jArray = array();
foreach($results as $key => $result) {
if(!in_array($result[0],$jArray) && !empty($result[0])) {
$jArray[$i] = $result[0];
$i++;
}
}
for($x = 0; $x < count($results); $x++) {
$k = array_search($results[$x][0],$jArray);
if(!isset($results[$x][1]))
$final[$k][1] = $results[$x][1];
if(!isset($results[$x][2]))
$final[$k][2] = $results[$x][2];
if(!isset($results[$x][3]))
$final[$k][3] = $results[$x][3];
if(!isset($results[$x][4]))
$final[$k][4] = $results[$x][4];
if(!isset($results[$x][5]))
$final[$k][5] = $results[$x][5];
if(!isset($results[$x][6]))
$final[$k][6] = $results[$x][6];
}
Any simpler ways of doing this?
You can do this way...
$new_arr=array();
$arkeys = array_unique(array_map(function ($v){ return $v[0];},$arr));
foreach($arr as $k=>$arr1)
{
$new_arr[$arr1[0]][]=array_slice($arr1,0,count($arr1)-1);
}
foreach($arkeys as $v)
{
$new_arr[$v] = call_user_func_array('array_merge', $new_arr[$v]);
}
print_r($new_arr);
OUTPUT :
Array
(
[Analyst] => Array
(
[0] => 21
[1] => 3
[2] => 12
[3] => 2
[4] => 12
[5] => 2
)
[Catalysis] => Array
(
[0] => 47
[1] => 8
)
[Biomaterials] => Array
(
[0] => 1
[1] => 0
)
)
Working Demo
If you just want to group by the first element of the sub array, a single loop is enough:
$result = array();
foreach ($array as $sub_arr) {
$key = $sub_arr[0];
unset($sub_arr[0]);
if (!isset($result[$key])) {
$result[$key] = array();
}
$result[$key] += $sub_arr;
}
Here
$final = array();
foreach($results as $key => $result) {
if (!in_array($result[0], array_keys( $final ) ) && !empty($result[0])) {
$final[$result[0]] = array( $result[0] );
}
foreach($result as $k => $v) {
if ($k != 0 && isset($v)) {
$final[$result[0]][$k] = $v;
}
}
}

Arrange PHP Multidimensional Array By Inner Index

How to arrange this array by last inner index ( 0, 1, 2 ) and get the value of the last inner index as the value of each second index:
Array
(
[text] => Array
(
[grid] => Array
(
[0] => 3
[1] => 4
[2] => 5
)
[image] => Array
(
[0] =>
[1] =>
[2] =>
)
[align] => Array
(
[0] => left
[1] => right
[2] => left
)
[title] => Array
(
[0] =>
[1] =>
[2] =>
)
[content] => Array
(
[0] =>
[1] =>
[2] =>
)
)
)
And have the results as below:
Array
(
[text] => Array
(
[0] => Array
(
[grid] => 3
[image] =>
[align] => left
[title] =>
[content] =>
)
[1] => Array
(
[grid] => 4
[image] =>
[align] => right
[title] =>
[content] =>
)
[2] => Array
(
[grid] => 5
[image] =>
[align] => left
[title] =>
[content] =>
)
)
)
This will do the work
function restructure($arr){
$newArr = array();
foreach($arr as $k => $v){
foreach($v as $k1 => $v1){
foreach($v1 as $k2 => $v2){
$newArr[$k][$k2][$k1] = $v2;
}
}
}
return $newArr;
}
As SiGanteng suggested, i dont see other ways than a for/foreach loop:
function buildArray($source, $key = false)
{
// Build the new array
$new_array = array();
// Define groups
$groups = $key === false ? array_keys($source) : array($key);
foreach($groups AS $group)
{
// Get the keys
$keys = array_keys($array[$group]);
// Count the values
$num_entries = count($array[$group][$keys[0]]);
for($i = 0; $i < $num_entries; $i++)
{
foreach($keys AS $key)
{
$new_array[$group][$i][$key] = $array[$group][$key][$i];
}
}
}
return $new_array;
}
This allow you to define the key you need to build; If not specified, the function build the array for every key.
This should work.
function formatit($arr) {
$new = array();
foreach($arr as $k=>$v) {
foreach($v as $k1=>$v1) {
$new[$k1][$k] = $v1;
}
}
return $new;
}
Tested. Call it as
$arr['text'] = formatit($arr['text']);
http://ideone.com/rPzuR

PHP: Modifying array recursively?

I have tried to make a function that iterates through the following array to flatten it and add parent id to children, where applicable. I just can't make it work, so I hope that anyone here has an idea of what to do:
Here's the starting point:
Array
(
[0] => Array (
[id] => 1
[children] => array (
[id] => 2
[children] => Array (
[0] => Array (
[id] => 3
)
)
)
)
The expected result :
Array (
[0] => array (
[id] => 1
)
[1] => array (
[id] => 2
)
[2] => array (
[id] => 3,
[parent] => 2
)
)
Hope that anyone can point me in the right direction. Thanks a lot!
Solution (Thanks to Oli!):
$output = array();
function dejigg($in) {
global $output;
if (!isset($in['children'])) {
$in['children'] = array();
}
$kids = $in['children'] or array();
unset($in['children']);
if (!isset($in['parent'])) {
$in['parent'] = 0; // Not neccessary but makes the top node's parent 0.
}
$output[] = $in;
foreach ($kids as $child) {
$child['parent'] = $in['id'];
dejigg($child); // recurse
}
return $output;
}
foreach ($array as $parent) {
$output[] = dejigg($parent);
}
$array = $output;
print("<pre>".print_r($array,true)."</pre>");
I've tested it this time. This does work!
$input = array( array('id' => 1, 'children'=>array( array('id'=>2, 'children'=>array( array('id'=>3) ) ) ) ) );
$output = [];
function dejigg($in) {
global $output;
$kids = $in['children'] or array();
unset($in['children']);
$output[] = $in;
foreach ($kids as $child) {
$child['parent'] = $in['id'];
dejigg($child); // recurse
}
}
foreach ($input as $parent)
dejigg($parent);
print_r($output);
And it returns:
Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 2
[parent] => 1
)
[2] => Array
(
[id] => 3
[parent] => 2
)
)

Categories