John Davidson

php - how to use explode for an array of objects

0 comments
Message:


I have an array like that:


array(5) {
["code"]=>
int(1)
["messageError"]=>
string(27) "La typologie est incorrecte"
["model"]=>
string(3) "lot"
["grp_regles"]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(3) {
["champ"]=>
string(21) "lot_surface_habitable"
["comparaison"]=>
string(7) "between"
["valeurAttendue"]=>
array(2) {
[0]=>
int(16)
[1]=>
int(40)
}
}
}
}
["prerequis"]=>
array(2) {
[0]=>
array(3) {
["champ"]=>
string(6) "typ_id"
["comparaison"]=>
string(1) "="
["valeurAttendue"]=>
int(1)
}
[1]=>
array(3) {
["champ"]=>
string(22) "tranche.fus.fup.fup_id"
["comparaison"]=>
string(1) "="
["valeurAttendue"]=>
int(1)
}
}
}

I want to do a foreach in "prerequis":


$modelRetrieve = $this->retrieveModel($model);
$modelFind = $modelRetrieve::find($id);
$arrayError=[];
$query = '';
$path = storage_path() . "/json/controle.json";
$json = file_get_contents($path);
foreach (json_decode($json,true) as $key => $value) {
$test = true;
var_dump($value);
if($value['model'] === $model ){
foreach ($value['prerequis'] as $key => $value2) {
if( $test && $modelFind[$value2['champ']] == (int)$value2["valeurAttendue"] )
{
$test = true;
}
}
}
}

I need in second foreach to use in $value2['champ'] where $value2['champ'] is "tranche.fus.fup_id. So I need to explode that to have ['tranche']['fus']['fup_id'].
How to use explode with that ?
thanks everyone :)



My Answer:
[0] => stdClass Object
(
[id] => 1
[name] => John
)

[1] => stdClass Object
(
[id] => 2
[name] => Jane
)

[2] => stdClass Object
(
[id] => 3
[name] => Alice
)

[3] => stdClass Object
(
[id] => 4
[name] => Bob
)

[4] => stdClass Object
(
[id] => 5
[name] => Mary
)
}

To use `explode` on an array of objects, you can loop through each object in the array and apply `explode` on a specific property of the object. For example, if you want to explode the `name` property of each object by space, you can do the following:

php
$explodedArray = [];
foreach ($array as $object) {
$explodedName = explode(' ', $object->name);
$object->name = $explodedName;
$explodedArray[] = $object;
}

print_r($explodedArray);


This code will explode the `name` property of each object in the array by space and store the exploded names in a new array called `$explodedArray`.

Rate this post

4 of 5 based on 5268 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us