Convert array of values to nested associative array [duplicate] - php

This question already has answers here:
php create multidimensional array from flat one
(4 answers)
Closed 4 years ago.
php create multidimensional array from flat one
Tried this but counting backwards won't work as I need to move from start to finish in the order in which the array is originally.
I have a simple array:
0 => Item #1
1 => Item #2
2 => Item #3
I need to create an associative array from the above like so:
Item #1
=> Item #2
=> Item #3
Where each value becomes the key for the parent item. This must be done in a while loop not recursion. It MUST move forward, the loop performs a look-ahead for validation purposes, so the original order is imperative
Thanks
EDIT - this is giving me the intended result I just can't get my around how to do this in the main loop |
array:3 [
0 => "workorder"
1 => "company"
2 => "name"
]
$array['workorder'] = [];
$temp = &$array['workorder'];
$temp['company'] = [];
$temp2 = &$temp['company'];
$temp2['name'] = [];
dump($array);
exit;
EDIT 2 | Main loop
$type = current($types);
while (array_key_exists($type, $this->types)) {
$nextType = next($types);
// ... do stuff
$type = $nextType;
}
return $array;

Try
// This array contain the keys for associative array
$arrayKeys = ['name1', 'name2', 'name3'];
// This array contain the values for associative array
$arrayItems = ['item1', 'item2', 'item3'];
// this array will be the associative array
$newArray = [];
$count = count($arrayKeys) -1;
while( $count >= 0 ){
$newArray[ $arrayKeys[$count] ] = $arrayItems[$count];
echo '<Br>';
$count--;
}

Related

How to convert a string to a multidimensional recursive array in PHP? [duplicate]

This question already has an answer here:
how to merge multiple url/path into multidimensional array?
(1 answer)
Closed 8 months ago.
I have a problem with creating a recursive array with PHP.
I need to format this string to a multidimensional array with the dot-separated elements indicating multiple levels of array keys.
$str = "code.engine,max_int.4,user.pre.3,user.data.4";
The output for this example would be:
$str = array(
"code" => "engine",
"max_int" => 4,
"user" => array(
"pre" => 3,
"data" => 4
)
);
I will start with an explode function, but I don't know how to sort it from there, or how to finish the foreach.
You could start to split using comma ,, then, split each item by dot ., remove the last part to get the "value", and the rest as "path". Finally, loop over the "path" to store the value:
$str = "code.engine,max_int.4,user.pre.3,user.data.4";
$array = [] ;
$items = explode(',',$str);
foreach ($items as $item) {
$parts = explode('.', $item);
$last = array_pop($parts);
// hold a reference of to follow the path
$ref = &$array ;
foreach ($parts as $part) {
// maintain the reference to current path
$ref = &$ref[$part];
}
// finally, store the value
$ref = $last;
}
print_r($array);
Outputs:
Array
(
[code] => engine
[max_int] => 4
[user] => Array
(
[pre] => 3
[data] => 4
)
)

Array display without key [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 6 years ago.
I am trying to display an array without key item. Just want to display array values without key.
Here is my sample code I tried
$myList = array(
0 =>array(
"product_id"=> 8085
),
1 =>array(
"product_id"=> 8087
),
2 =>array(
"product_id"=> 8086
),
3 =>array(
"product_id"=> 8042
),
);
$newList = array();
foreach($myList as $listItem) {
$newList[] = $listItem['product_id'];
}
$a=array();
$a= array_values($newList);
print_r($a);
I want my array like this
$productIds = array(8085,8087,8086,8042);
Here is my sample code link
You're looking for array_column (which is available as of PHP 5.5):
$productIds = array_column($myList, 'product_id');
This gives you:
var_export($productIds);
array (
0 => 8085,
1 => 8087,
2 => 8086,
3 => 8042,
)
Which is exactly what you want:
var_dump($productIds === array(8085,8087,8086,8042)); // bool(true)
print_r function will output the keys. even if you use array_values the array still have indexes as keys.
Just output the the array manually using echo and implode (implode will join array values into a single string using the first parameter character):
echo implode(',', $newList);
Arrays will always have keys. If you want an array, you can get all the values, turn them into one comma separated string, and place that into an array:
$productIds = [implode(',', array_column($myList, 'product_id'))];
var_dump($productIds);
// RESULT:
// array (size=1)
// 0 => string '8085,8087,8086,8042' (length=19)

How to count numbers of keys in an array of objects [duplicate]

This question already has answers here:
php - Is it possible to count the number of keys in an array?
(4 answers)
Closed 6 years ago.
I am using laravel 5, I need count the keys available inside every array index suppose for array[0] it has 7 keys, now I need the last key and before last key to compare which's value is bigger. how I can do using loop,as far I have tried.
Please Note The inner keys are stored as object key=>value pair.
foreach ($regions as $regions_key => $regions_value) {
echo sizeof($regions_key)
}
Help is appreciated.
Wouldn't you just count it within your loop:
$total = 0;
foreach($data as $sub_array) {
$total += count($sub_array);
}
After the above iteration is done to find your counts, $total will hold your count.
Example/Demo
Try this:
$countArr = array();
foreach ($regions as $regions_key => $regions_value) {
$countArr[$regions_key] = count($regions[$regions_key]); // create array of length of sub array
}
echo max($countArr); // max — Find highest value
To count the number of keys in an array. Try
$arr = Array
(
0 => 'hello',
1 => 'there',
2 => null,
3 => null,
4 => 3,
);
var_dump(count($arr));

How do I access each value in array? [duplicate]

This question already has answers here:
how to extract a column from mysql result set?
(2 answers)
Closed 5 months ago.
I have attempted numerous times trying access each value in a array. The array contains the database results retrieved from the select query.
$query = DB::getInstance()->query("SELECT orderStatus FROM customerOrders");
foreach ($query->results() as $orderered) {
$result_array = array($orderered);
//print_r($result_array);
$orderData = array_map(function ($object) { return $object->orderStatus; }, $result_array);
$test = json_decode(json_encode($result_array), true);
$ORvalue = serialize($test);
$ORvalue2 = unserialize($ORvalue);
$orderValueNEW = call_user_func_array('array_merge', $ORvalue2);
print_r($orderValueNEW);//debug
}//close foreach loop
Result it prints are:
Array ( [orderStatus] => 0 )
Array ( [orderStatus] => 0 )
Array ( [orderStatus] => 0 )
Array ( [orderStatus] => 1 )
Array ( [orderStatus] => 1 )
What you're doing should work to retrieve each row, but if you want to access the orderStatus value, you can do this with your result array:
foreach ($result_array as $resultRow) {
echo $resultRow['orderStatus'];
}
That should work, if that's what you mean. If you want to access the orderStatus value in the first loop, you can refer to it as $row['orderStatus']. Or, if you do a SELECT * in your query and you want to go through all values from the query, you can just make another loop like foreach ($row as $column => value) { ... }
Are you looking to just print the values and not the associate key/value pairs?
Changing
$result_array[] = $row;
to
$result_array[] = $row['orderStatus'];
should do the trick.

php reassign array contents [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
any particular function or code to put this kind of array data
ori [0] => 43.45,33,0,35 [1] => 74,10,0,22 [2] => 0,15,0,45 [3] => 0,0,0,340 [4] => 12,5,0,0 [5] => 0,0,0,0
to
new [0] => 43.45,74,0,0,12,0 [1] => 33,10,15,0,5,0 [2] => 0,0,0,0,0,0, [3] => 35,22,45,340,0,0
As you can see, the first value from each ori are inserted into the new(0), the second value from ori are inserted into new(1) and so on
If $ori is an array of arrays, this should work:
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
$newArray = transpose($ori);
Note: from Transposing multidimensional arrays in PHP
If $ori is not an array of arrays, then you'll need to convert it first (or use the example by Peter Ajtai), like this:
// Note: PHP 5.3+ only
$ori = array_map(function($el) { return explode(",", $el); }, $ori);
If you are using an older version of PHP, you should probably just use the other method!
You essentially want to transpose - basically "turn" - an array. Your array elements are strings and not sub arrays, but those strings can be turned into sub arrays with explode() before transposing. Then after transposing, we can turn the sub arrays back into strings with implode() to preserve the formatting you want.
Basically we want to go through each of your five strings of comma separated numbers one by one. We take each string of numbers and turn it into an array. To transpose we have to take each of the numbers from a string one by one and add the number to a new array. So the heart of the code is the inner foreach(). Note how each number goes into a new sub array, since $i is increased by one between each number: $new[$i++][] =$op;
foreach($ori as $one) {
$parts=explode(',',$one);
$i = 0;
foreach($parts as $op) {
$new[$i++][] =$op;
}
}
$i = 0;
foreach($new as $one) {
$new[$i++] = implode(',',$one);
}
// print_r for $new is:
Array
(
[0] => 43.45,74,0,0,12,0
[1] => 33,10,15,0,5,0
[2] => 0,0,0,0,0,0
[3] => 35,22,45,340,0,0
)
Working example

Categories