populate php multidimenssional array with foreach loop - php

I need to create an array like the following:
$va_body=array(
"bundles" => array(
"$table.$elem" => array("convertCodesToDisplayText" => true),
"$table.$elem" => array("convertCodesToDisplayText" => true),
)
);
$table is a string that does not change and $elem is extracted from an array.
I got close with the following code, but it ends up with only the last value from $bund, $bund is an array with two values. I guess the array is redeclared in each loop?
$va_body=array(); // declare the array outside the loop
foreach ($bund as $elem ) {
$va_body['bundles'] = array($table.".".$elem=>array("convertCodesToDisplayText" => true));
}
$bund array has two elements "description" and "type_id".
$va_body['bundles'][] // Adding [] doesn't work as it modifies the expected outcome.
print_r($va_body) looks like this:
Array (
[bundles] => Array (
[ca_objects.type_id] => Array (
[convertCodesToDisplayText] => 1
)
)
)
I need it to be:
Array (
[bundles] => Array (
[ca_objects.description] => Array (
[convertCodesToDisplayText] => 1
)
[ca_objects.type_id] => Array (
[convertCodesToDisplayText] => 1
)
)
)
Thanks in advance.
#phpisuber01
Using:
$va_body['bundles'][] = array($table.".".$elem=>array("convertCodesToDisplayText" => true));
print_r($va_body); looks like this:
Array (
[bundles] => Array (
[0] => Array (
[ca_objects.description] => Array (
[convertCodesToDisplayText] => 1
)
)
[1] => Array (
[ca_objects.type_id] => Array (
[convertCodesToDisplayText] => 1
)
)
)
)
And I need it to be like this:
Array (
[bundles] => Array (
[ca_objects.description] => Array (
[convertCodesToDisplayText] => 1
)
[ca_objects.type_id] => Array (
[convertCodesToDisplayText] => 1
)
)
)
Answer by #phpisuber01:
$va_body['bundles'][$table.".".$elem] = array("convertCodesToDisplayText" => true);
Thank you very much!

You need to make an array of arrays. In your loop change the following line:
$va_body['bundles'][$table.".".$elem] = array("convertCodesToDisplayText" => true);
Added [] after $va_body['bundles'].
All this does is keep adding the new bundles into the array. Your original code is overwriting bundles each iteration. That's why you only get the last one.
Updated to get closer to OP's exact needs.

$va_body = array();
$va_body['bundles'] = array();
foreach ($bund AS $elem)
{
$va_body['bundles']["{$table}.{$elem}"] = array("convertCodesToDisplayText" => true);
}

Related

Convert comma separated array to nested array with php function

I need to convert array_1 to array_2 with a PHP function. I tried many things but nothing works. I hope someone can help me out here. I think I need an each function or something to loop through the comma separated array and convert it into the array_2.
$array_1 = array (
0 => '6801,6800,7310,6795',
);
$array_2 = array (
0 =>
array (
0 => '6801',
1 => '6800',
2 => '7310',
3 => '6795',
),
);
Here a solution
<?php
$array_1 = array (
0 => '6801,6800,7310,6795',
);
$array_2 = array();
foreach ($array_1 as $value) {
array_push($array_2 , explode(",",$value));
}
print_r($array_2);
?>
The output that i got
Array ( [0] => Array ( [0] => 6801 [1] => 6800 [2] => 7310 [3] => 6795 ) )
Use PHP explode function. https://www.php.net/manual/de/function.explode.php
$newArray[] = explode(",", $array_1[0]);
// output
Array
(
[0] => Array
(
[0] => 6801
[1] => 6800
[2] => 7310
[3] => 6795
)
)
Just create a new array with a value returned by the explode function. Reset always returns the first value of the array regardless of the key.
$array_1 = array (0 => '6801,6800,7310,6795');
$newArray = [explode(",", reset($array_1))];

How to update an Associative Array

I do not know what is wrong with my php code. I want to have an Associative Array in the format. When I run my code I get this data. [KY] is an array in the [OH] array.
Array ( [Oh] => Array ( [state] => Oh ) [income] => 100 [count] => 1 [Ky] => Array ( [state] => Ky ) )
Array (
[OH] => Array
( [income] =>
[count] =>
)
[KY] => Array
( [income] =>
[count] =>
)
Here is my code
Example data in $array
Array ( [0] => Array (
[SurveyDate] => 1952-06-21
[Income] => 100
[CountyState] => Hamilton|Oh
[count] => 1 ) )
function update_array_value3( $array )
{
foreach ($array as $row)
{
$arrCountyState = explode( "|", $row['CountyState'] );
$key = $arrCountyState[1]; // OH or KY
if( !isset( $_SESSION['sIncome'][$key] ) )
{
$_SESSION['sIncome'][$key]['state'] = $key;
$_SESSION['sIncome'][$key]['income'] = $row['Income'];
$_SESSION['sIncome'][$key]['count'] = 1;
} else
{
$_SESSION['sIncome'][$key]['state'] = $key;
$_SESSION['sIncome'][$key]['income'] += $row['Income'];
$_SESSION['sIncome'][$key]['count'] += 1;
}
}
I can't tell you the root cause of the problem simply based on this snippet of code, but it seems $row either doesn't contain the data you expect it to, or doesn't contain any data.
In your code you reference $row['CountyState'], yet I don't see any array item called CountyState in $array.
Also, I'm not sure whether or not this is intentional, but in your foreach() loop it looks like $_SESSION['sIncome']['income'] and $_SESSION['sIncome']['count'] are being overwritten. Each time the loop encounters a new $key, it will overwrite those values.

How to get the value of an element from a multidimensional JSON string array in PHP

This is the array:
Array
(
[0] => Array
(
[product_details] => {"5f93f983524def3dca464469d2cf9f3e":{"id":"110","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":1400,"name":"Foot Massage","tax":null,"image":"http:\/\/acme.dev\/uploads\/product_image\/product_110_1_thumb.jpg","coupon":"9","book_date_":"2017-04-19","book_date_name_":"wed","start_timeslot_":"09:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"5f93f983524def3dca464469d2cf9f3e","subtotal":1400}}
)
[1] => Array
(
[product_details] => {"2723d092b63885e0d7c260cc007e8b9d":{"id":"109","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":700,"name":"Body Massage","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/product_109_1_thumb.jpg","coupon":"","book_date_":"2017-04-18","book_date_name_":"tue","start_timeslot_":"09:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"2723d092b63885e0d7c260cc007e8b9d","subtotal":700}}
)
[2] => Array
(
[product_details] => {"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id":"108","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":3000,"name":"Alo","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/default.jpg","coupon":"","book_date_":"2017-04-21","book_date_name_":"fri","start_timeslot_":"10:00:00","end_timeslot_":"12:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"a3c65c2974270fd093ee8a9bf8ae7d0b","subtotal":3000}}
)
[3] => Array
(
[product_details] => {"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id":"108","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":3000,"name":"Alo","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/default.jpg","coupon":"","book_date_":"2017-04-12","book_date_name_":"wed","start_timeslot_":"08:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"a3c65c2974270fd093ee8a9bf8ae7d0b","subtotal":3000}}
)
)
What I need is to create a new simple array containing the values from all the "id" elements.
Hope this simple foreach will be helpful for you.
Solution 1: Try this code snippet here
$result=array();
foreach($array as $value)
{
$array= json_decode($value["product_details"],true);
$result[]=$array[key($array)]["id"];
}
print_r($result);
Here we are using array_column to extract product_details then we are using to array_map to iterate over $personalDetails which contain all the JSON's then we are using to key function which will return first key of the array, and through that key we are accessing, its id.
Solution 2: Try this code snippet here
<?php
ini_set('display_errors', 1);
$array = Array
(
0 => Array
(
"product_details" => '{"5f93f983524def3dca464469d2cf9f3e":{"id":"110","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":1400,"name":"Foot Massage","tax":null,"image":"http:\/\/acme.dev\/uploads\/product_image\/product_110_1_thumb.jpg","coupon":"9","book_date_":"2017-04-19","book_date_name_":"wed","start_timeslot_":"09:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"5f93f983524def3dca464469d2cf9f3e","subtotal":1400}}'
),
1 => Array
(
"product_details" => '{"2723d092b63885e0d7c260cc007e8b9d":{"id":"109","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":700,"name":"Body Massage","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/product_109_1_thumb.jpg","coupon":"","book_date_":"2017-04-18","book_date_name_":"tue","start_timeslot_":"09:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"2723d092b63885e0d7c260cc007e8b9d","subtotal":700}}'
),
2 => Array
(
"product_details" => '{"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id":"108","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":3000,"name":"Alo","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/default.jpg","coupon":"","book_date_":"2017-04-21","book_date_name_":"fri","start_timeslot_":"10:00:00","end_timeslot_":"12:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"a3c65c2974270fd093ee8a9bf8ae7d0b","subtotal":3000}}'
),
3 => Array
(
"product_details" => '{"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id":"108","qty":1,"option":"{\"color\":{\"title\":\"Color\",\"value\":null}}","price":3000,"name":"Alo","tax":0,"image":"http:\/\/acme.dev\/uploads\/product_image\/default.jpg","coupon":"","book_date_":"2017-04-12","book_date_name_":"wed","start_timeslot_":"08:00:00","end_timeslot_":"10:00:00","has_already_rescheduled":0,"discount_":"0","rowid":"a3c65c2974270fd093ee8a9bf8ae7d0b","subtotal":3000}}'
)
);
$personalDetails= array_column($array, "product_details");
$result=array_map(function($value){
$array=json_decode($value,true);
return $array[key($array)]["id"];
}, $personalDetails);
print_r($result);
Output:
Array
(
[0] => 110
[1] => 109
[2] => 108
[3] => 108
)
use array_column and json_decode
$new_one = array_column($array,'product_details');
$new_array=[];
foreach($new_one as $key=>$row)
{
foreach(json_decode($row,true) as $key1=>$row1)
{
$new_array[]=$row1['id'];
}
}
print_r($new_array);
you may use array_map & array_value to achieve this,
here is a quick example, and you need to modify it to be fit with your needs :
$ar = [
0 => ['product_details' => '{"5f93f983524def3dca464469d2cf9f3e":{"id": 3}}'],
1 => ['product_details' => '{"2723d092b63885e0d7c260cc007e8b9d":{"id": 8}}'],
2 => ['product_details' => '{"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id": 5}}'],
3 => ['product_details' => '{"a3c65c2974270fd093ee8a9bf8ae7d0b":{"id": 1}}'],
];
$ar = array_map(function ($value) {
return array_values(json_decode($value['product_details'], true))[0]['id'];
}, $ar);
print_r($ar);
live demo : https://3v4l.org/koXee
Try this code, live demo
print_r(array_column(array_map(function($v){return current(json_decode($v));},array_column($array, 'product_details')), 'id'));
You "product_details" seems to be a JSON string. Loop through your array, decode the JSON and store the "id" in a new array.

group php array by subarray value

I want to group an array by a subarray's value. If I have an array like this:
Array
(
[0] => Array
(
[userID] => 591407753
[propertyA] => 'text1'
[propertyB] => 205
)
[1] => Array
(
[userID] => 989201004
[propertyA] =>'text2'
[propertyB] => 1407
)
[2] => Array
(
[userID] => 989201004
[propertyA] => 'text3'
[propertyB] => 1407
)
)
I want to sort to group this array by a subarray's value so I can have an array like this:
Array
(
[0]=>Array
(
[userID]=>59140775
[properties]=>Array
(
[0]=>text1
)
[propertyB]=>205
)
[1]=>Array
(
[userID]=>989201004
[properties]=>Array
(
[0]=>'text2'
[1]=>'text3'
)
[propertyB]=>1047
)
)
How can I make this?
Before I had tried this:
$result = array();
foreach ($userArray as $record)
{
$id=$record['userID'];
if(isset($result[$id]))
{
$result[$id]['propertyA'][]=array($record['propertyA']);
}
else {
$record["propertyA"]=array($record['propertyA']);
unset($record['tweet']);
$result[$id]=$record;
}
}
the problem was for the propertyA. I was an the result an additional property propertyA with the table like this:
Array
(
[0]=>Array (
[userID]=>989201004
[propertyA]=>'text2'
[properties]=>Array(
[0]=>'text2'
[1]=>'text3'
)
)
)
The following code should do the job. I hope it is self-explanatory:
$result = array();
foreach ($array as $record) {
if (!isset($result[$record['userID']])) {
$result[$record['userID']] = array(
'userID' => $record['userID'],
'properties' => array($record['propertyA']),
'propertyB' => $record['propertyB'],
);
}
else {
$result[$record['userID']]['properties'][] = $record['propertyA'];
}
}
$result = array_values($result);

PHP/MySQL: Recreate multidimensional array from existing array

I've got an multi-array (currently with objects) that I want to reorder based on a specific key/value.
Array
(
[0] => stdClass Object
(
[task_id] => 1
[task_title] => Title
[users_username] => John
)
[1] => stdClass Object
(
[task_id] => 2
[task_title] => Title
[users_username] => John
)
[2] => stdClass Object
(
[task_id] => 3
[task_title] => Title
[users_username] => Mike
)
)
I'd like to reorder it to get multi-arrays by user_name, so I can cycle through the task by username.
Array
(
[John] => Array
(
[0] => Array
(
[task_id] => 1
[title] => Title
)
[1] => Array
(
[task_id] => 2
[title] => Title
)
)
[Mike] => Array
(
[0] => Array
(
[task_id] => 3
[title] => Title
)
)
)
Is it possible to recreate my array to an array like that above?
Updated version of the code
<?php
$it0 = (object) array('task_id' => 1,'task_title' => 'Title','users_username' => 'John');
$it1 = (object) array('task_id' => 2,'task_title' => 'Title','users_username' => 'John');
$it2 = (object) array('task_id' => 3,'task_title' => 'Title','users_username' => 'Mike');
$array = array($it0,$it1,$it2);
$return = array();
foreach($array as $id => $value){
$return[$value->users_username][] = array('task_id' => $value->task_id,'title' => $value->task_title);
}
var_dump($return);
Yes, it is possible.
You'll have to loop through your current array and create a new array to do it.
example:
$new_array = array();
foreach ($array as $row)
{
$new_row = array(
'task_id' => $row->task_id,
'title' => $row->task_title,
);
$name = $row->users_username;
if (isset($new_array[$name]))
{
$new_array[$name][] = $new_row;
}
else
{
$new_array[$name] = array($new_row);
}
}
Now $new_array contains the new array exactly like the one you're asking for.
Then you can sort it with
ksort($new_array);
There may be another way to do this, with some built-in function, but sometimes I'd rather just do it myself, and know how it is working, without having to look up the documentation.
The approach:
Iterate through all of the first array, looking at [users_username] and putting them into a new array.
Code:
$dst_array = array();
foreach ($src_array as $val)
{
$user = $val->users_username;
// TODO: This check may be unnecessary. Have to test to find out.
// If this username doesn't already have an array in the destination...
if (!array_key_exists($user, $dst_array))
$dst_array[$user] = array(); // Create a new array for that username
// Now add a new task_id and title entry in that username's array
$dst_array[$user][] = array(
'task_id' => $val->task_id
'title' => $val->title
);
}
Just something like this (maybe not 100% PHP code):
foreach ( $obj : $oldArray ) {
$newTask['task_id'] = $obj->task_id;
$newTask['title'] = $obj->title;
$newArray[$oldName][] = $newTask;
}
If you want to order it; you can just call a order function afterwards.

Categories